今回の内容

機能説明
- Cellに表示したハート型のButtonを押すと、ButtonのBackgroundImageが変わります。
- Buttonの初期状態はハートの内側が白いです。押すとハート全体が青い画像に変わります。
コードと簡単解説
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {}
-
Cellの作成
-
cellHeartButtonをCellのUIButtonとして作成します。
-
cellHeartButton.tag = indexPath.row
は、Buttonが押された時にどのButtonが押されたか、判別するためにButtonにTagを設定しています。 -
cellHeartButton.addTarget(self, action: #selector(goodOrNoGood), for: .touchDown)
は、Buttonが押された時の処理を追加します。
let cellContentsArray = ["1","2","3","4","5","6","7","8","9","10"]
~~~一部省略~~~
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let cellContentsLabel = cell.contentView.viewWithTag(1) as! UILabel
let cellHeartButton = cell.contentView.viewWithTag(2) as! UIButton
cellContentsLabel.text = cellContentsArray[indexPath.row]
cellHeartButton.tag = indexPath.row
cellHeartButton.addTarget(self, action: #selector(goodOrNoGood), for: .touchDown)
return cell
}
#selector(goodOrNoGood)
-
if sender.backgroundImage(for: .normal) == UIImage(systemName: "heart"){}
では、Buttonの画像がUIImage(systemName: "heart")
の時はUIImage(systemName: "heart.fill")
に変化させます。
goodOrNoGood
@objc func goodOrNoGood(sender:UIButton){
if sender.backgroundImage(for: .normal) == UIImage(systemName: "heart"){
sender.setBackgroundImage(UIImage(systemName: "heart.fill"), for: .normal)
print(sender.tag)
}else{
sender.setBackgroundImage(UIImage(systemName: "heart"), for: .normal)
print(sender.tag)
}
}
終わり
ご指摘、ご質問などありましたら、コメントまでお願い致します。