ios - uibutton点击事件 - uibutton swift




UIButton的addTarget选择器不工作 (4)

我想这个问题是你如何设置按钮的布局。 尝试这个:

func createBoxes() {
    stack.backgroundColor = UIColor.red
    for _ in 0..<xy {
        // Create the button
        let button = UIButton()
        button.backgroundColor = UIColor.red

        // Add constraints
        button.translatesAutoresizingMaskIntoConstraints = false
        button.heightAnchor.constraint(equalToConstant: 44.0).isActive = true
        button.widthAnchor.constraint(equalToConstant: 44.0).isActive = true

        // Setup the button action
        button.addTarget(self, action: #selector(SquareBox.click(sender:)), for: .touchUpInside)

        // Add the button to the stack
        stack.addArrangedSubview(button)
    }
}

@objc func click(sender : UIButton) {
    print("Click")
}

SquareBox.swift

class SquareBox {
  func createBoxes() {
    for _ in 0..<xy {
            let button = UIButton()

            button.backgroundColor = .white
            button.setTitleColor(UIColor.black, for: .normal)
            button.layer.borderWidth = 0.5
            button.layer.borderColor = UIColor.black.cgColor
            stack.addArrangedSubview(button)
            button.addTarget(self, action: #selector(click(sender:)) , for: .touchUpInside)
    }
  }

  @objc func click(sender : UIButton) {
    print("Click")
  }
}

ViewController.swift

class GameViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let boxRow = SquareBox() 
        boxRow.createBoxes()
    }
}

另外我已经尝试了@IBAction而不是@objc,它不起作用,但是如果我在ViewController.swift中使用“click”函数创建了这个对象,它就可以工作,但是我需要在这个类中使用这个函数。


替换为:

    btn.addTarget(self, action: #selector(self.click(sender:)), for: .touchUpInside)

我认为别的东西会影响到你的选择器方法,因为你的代码也在我的项目中工作,所以试着在你的代码中找到。


 var btnfirst:UIButton!
 override func viewDidLoad() 
 {
    super.viewDidLoad()
    btnfirst = UIButton(type: .system)
    btnfirst.setTitle("Press", for: .normal)
    btnfirst.setTitleColor(.red, for: .normal)
    btnfirst.frame = CGRect(x: 100, y: 200, width: 100, height: 30)
    btnfirst.addTarget(self, action: #selector(benpress( sender:)),for: .touchUpInside)
    self.view.addSubview(btnfirst)
}

func benpress( sender :UIButton) 
{
  //Your Code Here                       
}

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

func click(sender : UIButton) {
       // code here
    }




uibutton