gpt4 book ai didi

ios - 带有按钮 addTarget 事件的标签不会触发

转载 作者:行者123 更新时间:2023-11-28 15:35:49 26 4
gpt4 key购买 nike

我在表格 View 单元格中有一个标签。标签有文本文本的结尾有一个按钮,该按钮代表用户喜欢的按钮。一切正常,但问题是 hitForLike 未触发。按钮单击事件未触发。我错过了什么吗

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)

}

最佳答案

我认为您需要在标签上启用用户交互,如下所示:

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

希望对您有所帮助。

关于ios - 带有按钮 addTarget 事件的标签不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44279335/

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