在Swift中以编程方式创建一个UIButton [英] Make a UIButton programmatically in Swift
本文介绍了在Swift中以编程方式创建一个UIButton的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试以编程方式构建UI。如何让这个动作起作用?我正在使用Swift开发。
I am trying to build UI's programmatically. How do I get this action working? I am developing with Swift.
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 = 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();
}
推荐答案
你只是错过了选择器名称末尾的冒号。由于按下了参数,冒号必须在那里。你的被按下的函数也不应该嵌套在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 = 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: #selector(myClass.pressed(_:)), forControlEvents: .TouchUpInside)
self.view.addSubview(myFirstLabel)
self.view.addSubview(myFirstButton)
}
@objc func pressed(sender: UIButton!) {
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.
这篇关于在Swift中以编程方式创建一个UIButton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文