【问题标题】:addTarget on a Custom UI Button not working programmatically自定义 UI 按钮上的 addTarget 无法以编程方式工作
【发布时间】:2020-09-04 12:41:27
【问题描述】:

我用这个初始化器创建了一个自定义 UIButton:

class CustomButton : UIButton{


override init(frame: CGRect) {
    super.init(frame: frame)
    setUpButtoninClass(frame)

    addTarget(self, action: #selector(handleTap), for:.touchUpInside )

}




fileprivate func setUpButtoninClass(_ frame: CGRect) {
    let padding : CGFloat = 16



    self.frame = frame
    layer.shadowColor = UIColor.darkGray.cgColor
    layer.shadowOpacity = 0.3
    layer.shadowOffset = .zero
    layer.shadowRadius = 10
    layer.cornerRadius = frame.width/2
    backgroundColor = UIColor(white: 0.9, alpha: 1)

    let buttonView = UIView(frame: frame)

    buttonView.layer.cornerRadius = frame.width/2
    buttonView.backgroundColor = .white
    addSubview(buttonView)

    let imageView = UIImageView(image: UIImage(named: "pen")?.withRenderingMode(.alwaysTemplate))
    imageView.tintColor = UIColor(white: 0.7, alpha: 1)
    buttonView.addSubview(imageView)
    imageView.anchor(top: buttonView.topAnchor, leading: buttonView.leadingAnchor, bottom: buttonView.bottomAnchor, trailing: buttonView.trailingAnchor, padding: UIEdgeInsets.init(top: padding, left: padding, bottom: padding, right: padding))

}

@objc func handleTap(){
    print("I'm here")
}


required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")

}}

在初始化程序中,我添加了一个目标,但是当我实际初始化 VC 中的自定义按钮时,#selector 方法 (handleTap)没有被调用

这是自定义Button在VC中的实现:

class ViewController: UIViewController {


let circularButton = CustomButton(frame: CGRect(x: 0, y: 0, width: 70, height: 70))


override func viewDidLoad() {
    super.viewDidLoad()
    self.view.addSubview(circularButton)
    circularButton.center = view.center
}

我还尝试在 VC 中初始化 CustomButton 时添加目标,但没有任何改变。 我想知道我在设置按钮时哪里出错了。

编辑 1: 这是调试视图层次结构

【问题讨论】:

  • 发布视图的调试视图层次结构。
  • 我在 EDIT 1 中添加了它
  • 您的UIViewUIImageView 可能会占用您的触摸。尝试将他们的 userInteractionEnabled 都设置为 false。
  • 这确实有效!我其实应该考虑一下的。非常感谢!

标签: ios swift uibutton uikit addtarget


【解决方案1】:

天啊,调试完你的代码后,buttonViewimageView 在顶部。按钮在后面。您可以设置颜色以更轻松地对其进行调试。删除上面的2个视图让你的代码完美运行

【讨论】:

    【解决方案2】:

    我认为这是你的错, 未检测到触摸,因为您在 UIButton 的顶部添加了一个 ImageView。
    试试这个,或者这个,

    buttonView.isUserInteractionEnabled = true
    imageView.isUserInteractionEnabled = true
    

    【讨论】:

    • 试试这个,button.addTarget(self, action: #selector(action(sender:)), for: .touchUpInside)。 @objc func action(sender: UIButton) { }
    • 还有这个按钮不会调用handleTap函数
    • 感谢@Rikh 在问题下的评论,我解决了问题
    猜你喜欢
    • 2017-12-06
    • 2015-01-16
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-31
    相关资源
    最近更新 更多