2017-05-31 14 views
0

我在tableview單元格中有一個標籤。標籤具有文本結尾的文本有一個按鈕代表用戶喜歡的按鈕。一切都很好,但問題是hitForLike不fire.button點擊事件不起火。我是否錯過了什麼帶按鈕的標籤addTarget事件不會觸發

var titleLabel : UILabel = { 
     var label = UILabel() 
     label.font = UIFont.systemFont(ofSize: 21) 
     label.translatesAutoresizingMaskIntoConstraints = false 
     return label 
    }()  

func hitForLike(_ sender : UIButton){ 

     print("i miss you ....") 

    } 

func titleWithLikeButton(title:String,isFavorite : Bool){ 

      titleLabel.text = title 

     let button = UIButton(frame: CGRect(x: titleLabel.intrinsicContentSize.width, y: 0, width: 44, height: 44)) 

     //setup your button here 
     button.setTitleColor(UIColor.red, for: UIControlState.normal) 
     let image = UIImage(named: "heart-empty.png") 
     button.setImage(image, for: UIControlState.normal) 

     button.addTarget(self, action: #selector(hitForLike(_:)), for: UIControlEvents.touchUpInside) 

     //Add the button to the text label 
     titleLabel.addSubview(button) 

} 
+2

集label.userinteractionenabled ==真和檢查 –

+0

感謝@ Anbu.Karthik –

回答

1

我認爲你需要讓用戶交互的標籤上,就像這樣:

titleLabel.isUserInteractionEnabled = true 

所以整個函數結束這樣看:

func titleWithLikeButton(title:String,isFavorite : Bool){ 
    titleLabel.text = title 
    titleLabel.isUserInteractionEnabled = true //enable userinteraction 

    let button = UIButton(frame: CGRect(x: titleLabel.intrinsicContentSize.width, y: 0, width: 44, height: 44)) 

    //setup your button here 
    button.setTitleColor(UIColor.red, for: UIControlState.normal) 
    let image = UIImage(named: "heart-empty.png") 
    button.setImage(image, for: UIControlState.normal) 

    button.addTarget(self, action: #selector(hitForLike(_:)), for: UIControlEvents.touchUpInside) 

    //Add the button to the text label 
    titleLabel.addSubview(button) 
} 

希望有所幫助。

0

你必須設置你的按鈕目標func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell,象下面這樣:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 


     let cell = tableViewForPAC.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell 
     cell.yourButton.tag = indexpath.row 
     cell.yourButton.addTarget(self, action: #selector(hitForLike(_:)), for: UIControlEvents.touchUpInside) 
     return cell 

} 

func hitForLike(_ sender : UIButton){ 

     print(sender.tag) 
     print("i miss you ....") 

    }