2017-07-15 55 views
1

UITableViewCell中的按钮在其单击的方法内不响应setImage方法。这里是TableView的cellForRowAt部分。TableViewCell中的UIButton单击后无法设置图像

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell=tableView.dequeueReusableCell(withIdentifier: "BroadcastViewCell", for: indexPath) as!BroadcastViewCell 
    var show=self.week?[selectedIndex].shows?[indexPath.item] 
    cell.myLabel.text=show?.programName 
    if let resim=show?.thumbURL{ 
     cell.myImage.downloadImage(from: resim) 
    } 
    cell.notifyButton.tag = indexPath.row 
    cell.notifyButton.setImage(UIImage(named:"icnAlarm"), for: .normal) 
    cell.notifyButton.setImage(UIImage(named:"icnAlarmCheck"), for: .selected) 

    if (self.notifications?.contains(where: {$0.identifier == (show?.airDate)!+(show?.airTime)!}))! 
    { 
     cell.notifyButton.isSelected=true 
    }else 
    { 
     cell.notifyButton.isSelected=false 
    } 
    cell.notifyButton.addTarget(self, action: #selector(buttonClicked(sender:)), for: .touchUpInside) 
    return cell; 
} 

而我只是在buttonClicked实现中设置了它的选定状态。

func buttonClicked(sender:UIButton) 
{ 
    sender.isSelected=true 
} 

但是图像在它后面没有改变。它仅在其特定行的cellForRowAt方法调用之后发生更改。我不明白为什么它对同一代码部分的反应不同。谢谢你的帮助。

+0

见我回复此帖 - (链接)[https://stackoverflow.com/questions/44393575/checkbox-uitableview-with-differ ent-sections/44398444#44398444] - 它在UITableViewCell中为UIButton使用两个图像来创建一个Selected/Un-Selected“CheckBox”,它应该非常接近你想要做的事情。 – DonMag

回答

0

你必须告诉按钮要做什么:

func buttonClicked(sender:UIButton) 
{ 
    if myButton.isSelected { 
     myButton.isSelected = false 
    }else{ 
     myButton.isSelected = true 
    } 
} 

配置您的按钮进行定制:

let myButton = UIButton(type: .custom) 

或者在属性检查器:

attributes Inspector forbutton

+0

已选中已在我的版本中更名为isSelected,并且在cellForRowAt方法中也设置了isSelected true作品。 – umutg4d

+0

问题:你的buttonClicked方法是否被触发?并顺便尝试将您的按钮类型设置为自定义 –

+0

是的,它被触发。此外,当我打开调试视图层次结构,我可以看到按钮图像成功更改。但它不会对实际设备中的这种更改做出响应。 – umutg4d