gpt4 book ai didi

ios - 带有 UIButton : unable to change UIImage 的自定义 UITableViewCell

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:47:12 26 4
gpt4 key购买 nike

我有一个自定义 UITableView 和自定义 UITableViewCell 它包含一个 UIButton 我想在用户选择它时更改所选按钮的背景图像,

不幸的是,每当我按下它时图像都没有改变状态,它显示:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIView setBackgroundImage:forState:]:

这是我的代码片段:

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
static NSString *CellIdentifier = @"BTSTicketsCellIdentifier";
CRIndCategCell *cell = (CRIndCategCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil)
{
//Initialize cell
}

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

...
...
...

}

-(IBAction)AddToFav:(id)sender{
NSLog(@"Value of selected button = %ld",(long)[sender tag]);

UIButton *Btn=(UIButton*)[self.view viewWithTag:(long)[sender tag]];
[Btn setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
[Btn setBackgroundImage:[UIImage imageNamed:@"grey-star.png"] forState:UIControlStateNormal];


}

我的日志正确显示所选按钮的值但无法更改按钮的图像

感谢您的阅读。

最佳答案

尝试将您的 AddToFav: 方法修改为:

-(IBAction)AddToFav:(UIButton *)sender{
NSLog(@"Value of selected button = %ld",(long)[sender tag]);

[sender setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
[sender setBackgroundImage:[UIImage imageNamed:@"grey-star.png"] forState:UIControlStateNormal];


}

或者使用这个:

-(IBAction)AddToFav:(UIButton *)sender{
NSLog(@"Value of selected button = %ld",(long)[sender tag]);
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
for (UIButton *btn in [cell.contentView.superview subviews] ) {
if ([btn isKindOfClass:[UIButton class]]&& btn.tag ==(long)[sender tag]) {
[btn setBackgroundImage:[UIImage imageNamed:@"grey-star.png"]
}
}
}

关于ios - 带有 UIButton : unable to change UIImage 的自定义 UITableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20394486/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com