Make a UIButton programmatically in Swift

后端 未结 19 1778
死守一世寂寞
死守一世寂寞 2020-11-27 10:00

I am trying to build UI\'s programmatically. How do I get this action working? I am developing with Swift.

Code in viewDidLoad:

over         


        
19条回答
  •  攒了一身酷
    2020-11-27 10:41

    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()
    }
    

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

提交回复
热议问题