在 Swift 中以编程方式制作 UIButton

在 Swift 中以编程方式制作 UIButton

问题描述:

我正在尝试使用 Swift 以编程方式构建 UI.

I am trying to build UIs programmatically with Swift.

我怎样才能让这个动作起作用?

How can I get this action working?

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let myFirstLabel = UILabel()
    let myFirstButton = UIButton()
    myFirstLabel.text = "I made a label on the screen #toogood4you"
    myFirstLabel.font = UIFont(name: "MarkerFelt-Thin", size: 45)
    myFirstLabel.textColor = UIColor.redColor()
    myFirstLabel.textAlignment = .Center
    myFirstLabel.numberOfLines = 5
    myFirstLabel.frame = CGRectMake(15, 54, 300, 500)
    myFirstButton.setTitle("✸", forState: .Normal)
    myFirstButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
    myFirstButton.frame = CGRectMake(15, -50, 300, 500)
    myFirstButton.addTarget(self, action: "pressed", forControlEvents: .TouchUpInside)
    self.view.addSubview(myFirstLabel)
    self.view.addSubview(myFirstButton)
}

func pressed(sender: UIButton!) {
    var alertView = UIAlertView();
    alertView.addButtonWithTitle("Ok");
    alertView.title = "title";
    alertView.message = "message";
    alertView.show();
}

您只是缺少选择器名称末尾的冒号.由于 press 需要一个参数,所以冒号必须在那里.此外,您按下的函数不应嵌套在 viewDidLoad 中.

You're just missing the colon at the end of the selector name. Since pressed takes a parameter the colon must be there. Also your pressed function shouldn't be nested inside viewDidLoad.

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let myFirstLabel = UILabel()
    let myFirstButton = UIButton()
    myFirstLabel.text = "I made a label on the screen #toogood4you"
    myFirstLabel.font = UIFont(name: "MarkerFelt-Thin", size: 45)
    myFirstLabel.textColor = .red
    myFirstLabel.textAlignment = .center
    myFirstLabel.numberOfLines = 5
    myFirstLabel.frame = CGRect(x: 15, y: 54, width: 300, height: 500)
    myFirstButton.setTitle("✸", for: .normal)
    myFirstButton.setTitleColor(.blue, for: .normal)
    myFirstButton.frame = CGRect(x: 15, y: -50, width: 300, height: 500)
    myFirstButton.addTarget(self, action: #selector(pressed), for: .touchUpInside)
}

@objc func pressed() {
    var alertView = UIAlertView()
    alertView.addButtonWithTitle("Ok")
    alertView.title = "title"
    alertView.message = "message"
    alertView.show()
}

更新以反映 Swift 2.2 中的最佳实践.应该使用 #selector() 而不是不推荐使用的文字字符串.

Updated to reflect best practices in Swift 2.2. #selector() should be used rather than a literal string which is deprecated.