【问题标题】:How to pass string in objective-c instance method?如何在objective-c实例方法中传递字符串?
【发布时间】:2010-11-14 19:49:21
【问题描述】:

您好,我有多个 UIButton(foobar),当按下时,每个都会调用不同的实例方法(doSomethingFoodoSomethingBar)。这是我正在工作的代码:

CGRect fooImageRect = CGRectMake(38.0f, 192.0f, 130.0f, 25.0f);
    UIButton *buttonFoo = [[UIButton alloc] init];
    buttonFoo.frame = fooImageRect;
    [buttonFoo setImage:[UIImage imageNamed:@"button_foo_130x25.png"] forState:UIControlStateNormal];
    [buttonFoo addTarget:self action:@selector(doSomethingFoo:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buttonFoo];
    [buttonFoo release];

CGRect barImageRect = CGRectMake(172.0f, 192.0f, 130.0f, 25.0f);
    UIButton *buttonBar = [[UIButton alloc] init];
    buttonBar.frame = barImageRect;
    [buttonBar setImage:[UIImage imageNamed:@"button_bar_130x25.png"] forState:UIControlStateNormal];
    [buttonBar addTarget:self action:@selector(doSomethingBar:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buttonBar];
    [buttonBar release];

还有实例方法doSomethingFoodoSomethingBar

    -(void)doSomethingFoo:(id) sender {
    // code doing something with a NSString having value 'foo'
}

     -(void)doSomethingBar:(id) sender {
        // same code doing something with a NSString having value 'bar'
}

我要做的是创建一个方法(doSomething),当按下任一按钮时我可以调用它,并将我将引用的字符串(值'foo'或'bar')传递给它在方法中。我在语法上苦苦挣扎。

【问题讨论】:

    标签: iphone objective-c string methods


    【解决方案1】:

    您可以使用相同的方法来处理两个按钮,但您不能选择发送的参数。动作选择器必须是以下形式之一:

    - (void)action
    - (void)action:(id)sender
    - (void)action:(id)sender forEvent:(UIEvent *)event
    

    sender 是发送消息的控件。因此,您可以通过检查sender 来判断两个按钮中的哪一个发送了消息。直接进行检查的可能性是在您使用一些众所周知的值(#define 或其他常量)创建 UIButton 时设置它的 tag 属性,并在您的操作方法中检查该属性。

    【讨论】:

      【解决方案2】:

      只需创建一个名为 buttonTitle 的 NSString ivar 并像这样编写方法:

      // first set buttonTitle:
      self.buttonTitle = @"foo"; //for buttonfoo
      self.buttonTitle = @"bar",  // for buttonbar
      
      
      
      
      -(void)doSomething:(id) sender {
       NSString *title = self.buttonTitle;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多