目标C语言 ios uibutton添加目标,从同一视图传递选择器参数



我有点困在这里了…在编程上,我正在创建一个小表单作为子视图。在编程上,我添加了一个确认按钮,并添加了一个目标。但我希望能够获得传递给选择器功能的表单内容。这可能吗?看起来像这样:

Details = [[UIView alloc]initWithFrame:CGRectMake(40, 20, 250, 300)];
Details.backgroundColor = [UIColor whiteColor];
Details.layer.cornerRadius = 5;
Details.alpha = 0;
UILabel *NameLabel = [[UILabel alloc]initWithFrame:CGRectMake(60, 25, 75, 20)];
[NameLabel setText:@"Place Name:"];
[NameLabel setFont:[UIFont systemFontOfSize:12]];
[Details addSubview:NameLabel];
UITextField *NameTV = [[UITextField alloc]initWithFrame:CGRectMake(135, 25, 110, 20)];
NameTV.borderStyle = UITextBorderStyleRoundedRect;
NameTV.font = [UIFont systemFontOfSize:12];
[Details addSubview:NameTV];
confirm = [[UIButton alloc]initWithFrame:CGRectMake(100, 250, 75, 40)];
[confirm setTitle:@"Set Marker" forState:UIControlStateNormal];
[confirm setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
confirm.titleLabel.font = [UIFont systemFontOfSize:14];
[confirm setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[confirm addTarget:self action:@selector(confirmMarker://add text field data here) forControlEvents:UIControlEventTouchUpInside];
//attach an array to the button???
[Details addSubview:confirm];
- (void) confirmMarker:(NSString)someString{
    NSLog(@"%@", someString);
}

我的问题是当表单视图形成时目标被添加…所以someString会是空的即使有人写了一些东西然后点击了按钮。对吧?有办法做到这一点吗?谢谢…

也许我错过了一些东西,但为什么你需要通过选择器传递它,如果你已经有访问值?

- (void) confirmMarker:(NSString)someString{
    NSLog(@"%@", NameTv.text);
}

按钮的预设选择器传递自己作为变量,所以它发送的是:

- (void) confirmMarker:(id)sender{
    // Sender is the button that sent
    NSLog(@"%@", NameTv.text);
}

要使用自己的变量执行选择器,必须这样做:

IMP imp = [ob methodForSelector:selector];
void (*func)(id, SEL, NSString *) = (void *)imp;
func(ob, selector, @"stringToSend");

但是,如果你用按钮触发那个,你需要得到textView。文本首先传递它,所以为什么不直接使用方法一,面向按钮的标准回调:

- (void) confirmMarker:(id)sender {
    NSLog(@"%@", NameTv.text);
} 

不,不可能。选择器中的参数只有发送者本身(在你的例子中是按钮)。因此,您必须将所需的信息存储在其他地方,例如ivar。

最新更新