Swift攻击UIButton而没有响应

时间:2017-06-16 07:46:17

标签: ios swift

    addButton = UIButton(type: .custom)
    addButton.setTitle("add", for: .normal)
    addButton.setTitle("tapped", for: .highlighted)
    addButton.titleLabel?.font = UIFont.systemFont(ofSize: 12)
    addButton.backgroundColor = UIColor.lightGray
    addButton.translatesAutoresizingMaskIntoConstraints = false
    addButton.addTarget(self, action: #selector(dosome(_:)), for: .touchUpInside)
    let bottom_button: NSLayoutConstraint = NSLayoutConstraint(item: addButton, attribute: NSLayoutAttribute.bottom, relatedBy:NSLayoutRelation.equal, toItem:mainView, attribute:NSLayoutAttribute.bottom, multiplier:1.0, constant: -10)
    let right_button: NSLayoutConstraint = NSLayoutConstraint(item: addButton, attribute: NSLayoutAttribute.right, relatedBy:NSLayoutRelation.equal, toItem:mainView, attribute:NSLayoutAttribute.right, multiplier:1.0, constant: -20)
    let height_button: NSLayoutConstraint = NSLayoutConstraint(item: addButton, attribute: NSLayoutAttribute.height, relatedBy:NSLayoutRelation.equal, toItem:nil, attribute:.notAnAttribute, multiplier:1.0, constant: 20)
    let width_button: NSLayoutConstraint = NSLayoutConstraint(item: addButton, attribute: NSLayoutAttribute.width, relatedBy:NSLayoutRelation.equal, toItem:nil, attribute:.notAnAttribute, multiplier:1.0, constant: 35)
    addButton.addConstraint(height_button)
    addButton.addConstraint(width_button)
    mainView.addSubview(addButton)
    mainView.addConstraint(bottom_button)
    mainView.addConstraint(right_button)

@IBAction func dosome(_ sender: UIButton) {
    print("tttttt")
}

点击时,按钮的文字会在没有操作的情况下转到突出显示的标题。任何人都可以指出什么是错的?

3 个答案:

答案 0 :(得分:0)

使用addButton.isHighlighted = false它会起作用。

答案 1 :(得分:0)

试试这个,addButton = UIButton(type: .system)并设置theButton.adjustsImageWhenHighlighted = false;

答案 2 :(得分:0)

我刚刚尝试过,它运行正常。删除了约束,您可以根据您的要求添加约束。确保在此addButton上方没有tapGesture或userInteractionEnabled视图,这导致您的IBAction方法无法被调用。

        let addButton = UIButton(type: .custom)
        addButton.setTitle("add", for: .normal)
        addButton.setTitle("tapped", for: .highlighted)
        addButton.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        addButton.backgroundColor = UIColor.lightGray
        addButton.translatesAutoresizingMaskIntoConstraints = false
        addButton.addTarget(self, action: #selector(self.dosome(_:)), for: .touchUpInside)

        self.view.addSubview(addButton)


      func dosome(_ sender: UIButton) {
        print("tttttt")
      }