[英]Changing the title of a button inside a custom cell of my tableview
我有一個表格視圖,里面有一個單元格。 該單元格具有一個在customTableVIewCell類中聲明為這樣的按鈕。
@property (weak, nonatomic) IBOutlet UIButton *myButton;
在表視圖控制器內部,我正在為此按鈕設置方法。
[cell.myButton setTitle:@"Show cell number!" forState:UIControlStateNormal];
[cell.myButton addTarget:self action:@selector(myButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
我想隨時更改按鈕的標題。
現在考慮一下:我的表視圖中有三個單元格,即我的表有三行。 在每一行中,都有一個名為myButton的按鈕。
每當單擊它時,我都想根據按鈕所在的單元格號將按鈕的標題更改為1或2或3。
我嘗試了這個:
- (IBAction)myButtonClicked:(id)sender{
NSIndexPath *indexPath =[self.tableVIew indexPathForCell:(UITableViewCell *)[[sender superview] superview]];
NSUInteger row = indexPath.row;
NSLog(@"button was clicked for the following row %i", row);
}
但是,無論單擊單元格1或單元格2還是單元格3上的按鈕,這都是在控制台上打印“單擊了以下0行的按鈕”。 (單元格不過是表格行)
請幫我。
嘗試將按鈕標簽設置為-
cell.myButton.tag = indexPath.row;
在您的cellForRowAtIndexPath方法中。
然后在您的myButtonClicked方法中獲取發件人按鈕的標簽..然后做您想做的進一步的事情。
- (IBAction)myButtonClicked:(id)sender{
NSLog(@"button was clicked for the following row %i", sender.tag);
}
您可以只在IBAction中使用發送者:)
- (IBAction)myButtonClicked:(UIButton*)sender
{
[sender setTitle:@"show new title" forState:UIControlStateNormal];
}
在初始化單元格的方法cellForRowAtIndexPath中,添加此
cell.myButton.tag=indexPath.row;
[cell.myButton addTarget:self action:@selector(myButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
並更新您的myButtonClicked方法。
- (IBAction)myButtonClicked:(id)sender{
UIButton *btn=sender;
NSLog(@"button was clicked for the following row %i", btn.tag);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.