簡體   English   中英

如何在循環中設置UIButtons的動作?

[英]How to set UIButtons' actions in a loop?

我在UITableView的每個單元格中都有一個按鈕。 現在我想將每個按鈕綁定到函數中的操作方法:

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { ...}

這是我的嘗試代碼:

    NSString* functionNamePrefix = @"actionMethod_";
    NSString* functionName = [functionNamePrefix stringByAppendingString:[NSString stringWithFormat:@"%d",indexPath.row]];
    SEL selectorFromString = NSSelectorFromString(functionName);
    [button addTarget:self action:@selector(selectorFromString:) forControlEvents:UIControlEventTouchDown];

失敗的原因是:操作選擇器將“ selectorFromString”作為函數名稱,但是SEL由字符串轉換。

有什么建議嗎? TIA!

更好的方法是為所有按鈕分配相同的操作,然后在action方法中計算出按鈕按下時所在的行。 否則,如果您的單元格被重用,則每個按鈕將分配有多個操作,這將非常令人困惑。

您可以使用我對此問題的答案輕松確定按鈕或其他控件所在的行。

您應該將selectorFromString傳遞給action參數,而不是@selector(selectorFromString :)

NSString* functionNamePrefix = @"actionMethod_";
NSString* functionName = [functionNamePrefix stringByAppendingString:[NSString stringWithFormat:@"%d",indexPath.row]];
SEL selectorFromString = NSSelectorFromString(functionName);
[button addTarget:self action:selectorFromString forControlEvents:UIControlEventTouchDown];

如果要使用SEL selectorFromString作為按鈕的SEL selectorFromString器,則應將@selector(selectorFromString:)更改為selectorFromString

嘗試這種方式,因為您已經准備好使用選擇器:

[button addTarget:self action:selectorFromString forControlEvents:UIControlEventTouchDown];

以這種方式嘗試。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { ...}

[button setTag:indexPath.row];
[button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchDown];

buttonTapped

-(void)buttonTapped:(UIButton *)button{

     switch(button.tag){
     //Your code here
     }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM