简体   繁体   English

更改我的tableview的自定义单元格内的按钮的标题

[英]Changing the title of a button inside a custom cell of my tableview

I have a table view, inside which there is a cell. 我有一个表格视图,里面有一个单元格。 This cell has a button which is declared like this in the customTableVIewCell class. 该单元格具有一个在customTableVIewCell类中声明为这样的按钮。

@property (weak, nonatomic) IBOutlet UIButton *myButton;

inside the table view controller, i am setting method for this button. 在表视图控制器内部,我正在为此按钮设置方法。

[cell.myButton setTitle:@"Show cell number!" forState:UIControlStateNormal];
[cell.myButton addTarget:self action:@selector(myButtonClicked:) forControlEvents:UIControlEventTouchUpInside];

i want to change the title of the button whenever it is selected. 我想随时更改按钮的标题。

Now consider this: I have three cells in my table view, that is my table has three rows. 现在考虑一下:我的表视图中有三个单元格,即我的表有三行。 In each row, there is a button called myButton. 在每一行中,都有一个名为myButton的按钮。

Whenever it is clicked, i want to change the title of the button to 1 or 2 or 3 depending on the cell number in which the button exists. 每当单击它时,我都想根据按钮所在的单元格号将按钮的标题更改为1或2或3。

i tried this: 我尝试了这个:

- (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);
}

But this is printing "button was clicked for the following row 0" to the console, no matter the button on cell #1 or cell #2 or cell #3 were clicked. 但是,无论单击单元格1或单元格2还是单元格3上的按钮,这都是在控制台上打印“单击了以下0行的按钮”。 (cell is nothing but the table row) (单元格不过是表格行)

Please help me. 请帮我。

Try setting button tag as- 尝试将按钮标签设置为-

cell.myButton.tag = indexPath.row;

in your cellForRowAtIndexPath method.. 在您的cellForRowAtIndexPath方法中。

And in your myButtonClicked method get the tag of sender button.. and then do whatever you want to do further. 然后在您的myButtonClicked方法中获取发件人按钮的标签..然后做您想做的进一步的事情。

- (IBAction)myButtonClicked:(id)sender{

    NSLog(@"button was clicked for the following row %i", sender.tag);
}

you can just use the sender in the IBAction :) 您可以只在IBAction中使用发送者:)

- (IBAction)myButtonClicked:(UIButton*)sender
{
    [sender setTitle:@"show new title" forState:UIControlStateNormal];
}

In the method cellForRowAtIndexPath where you initialise the cell,add this 在初始化单元格的方法cellForRowAtIndexPath中,添加此

cell.myButton.tag=indexPath.row;
[cell.myButton addTarget:self action:@selector(myButtonClicked:) forControlEvents:UIControlEventTouchUpInside];

And update your myButtonClicked method. 并更新您的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM