点击按钮时将数据传递给方法

时间:2012-12-31 11:19:46

标签: objective-c ios annotations uibutton mapkit

我的iphone App中的地图视图页面的注释标记添加了一个按钮

UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton addTarget:self
                action:@selector(go_to_detail_page:)    
      forControlEvents:UIControlEventTouchUpInside];
annView.rightCalloutAccessoryView = rightButton; 

我的接收功能是

-(IBAction)go_to_detail_page:(id)sender;{
}

我的问题如下。我在我的页面上创建了很多标记,我想在按下特定的注释视图按钮时传递一个唯一的标识符,即使字符串也没问题。一旦按下注释,如何将字符串传递给go_to_detail_page方法?

4 个答案:

答案 0 :(得分:1)

使用rightButton.tag = 1 并在

-(IBAction)go_to_detail_page:(id)sender{
    UIButton *button = (UIButton *)sender;
    if(button.tag==1){//this is the rightButton
         //your logic goes here

    }
}

答案 1 :(得分:0)

嘿,您可以对UIButton进行子类化,并将NSString *成员标记为每个按钮实例。

答案 2 :(得分:0)

您可以将唯一标识符设置为按钮tag

UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton addTarget:self
                action:@selector(go_to_detail_page:)    
      forControlEvents:UIControlEventTouchUpInside];
annView.rightCalloutAccessoryView = rightButton; 
rightButton.tag == any unique number // it would act as unique identifier

并按如下方式检索

- (IBAction)go_to_detail_page:(id)sender;{

    UIButton *button = (UIButton *)sender;
    if(button.tag==unique identifier){
        // this is the rightButton
        // your logic
    }
    else
    {

    }
}

答案 3 :(得分:0)

在我的谦虚意见中,您可以有两种选择。

第一个选项是为每个按钮分配一个tag,然后在其操作中检索它。因此,例如,对于每个按钮,您将分配不同的标签。

rightButton.tag = // a tag of integer type

然后你会像这样使用

- (void)goToDetailedPage:(id)sender
{
    UIButton *senderButton = (UIButton *)sender;

    int row = senderButton.tag;        
    // do what you want with the tag
}

另一个选项是使用关联参考。通过它们,并且没有子类化UIButton,您可以创建一个属性(类型为NSString)并将其用作标识符。

要使用它们,请查看Subclass UIButton to add a property

这是一个相当复杂的概念,但通过它你会有很大的灵活性。

备注

您不需要使用IBAction。把空虚改为。 IBAction或IBOutlet旨在与IB(Interface Builder)一起使用。它们只是占位符。在引擎盖下,它们意味着无效。

使用驼峰表示法。例如,正如我在回答中所写,而不是go_to_detail_page,请使用goToDetailedPage

相关问题