0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

UITableViewCellに作ったButtonに機能を追加

Posted at

今回の内容

531A42CB-BA1F-493D-BC5E-4E850B3BE8ED_1_201_a.jpeg

機能説明

  • 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)
            
        }      
    }

終わり

ご指摘、ご質問などありましたら、コメントまでお願い致します。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?