Make a UIButton programmatically in Swift

后端 未结 19 1854
死守一世寂寞
死守一世寂寞 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:36

    In Swift We Can Make A button programmatically by writing this code in our viewcontroller.swift file...

    import UIKit
    
    class ViewController: UIViewController
    {  
    private let firstbutton:UIButton = UIButton()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.firstbutton = UIButton.buttonWithType(UIButtonType.Custom) as? UIButton
        self.firstbutton!.frame = CGRectMake(100, 200, 100, 100)
        self.firstbutton!.backgroundColor = UIColor.redColor()
        self.firstbutton!.setTitle("My Button", forState: UIControlState.Normal)
        self.firstbutton!.addTarget(self, action:#selector(self.firstButtonClicked), forControlEvents: .TouchUpInside)
        self.view.addSubview(firstbutton!)
        }
    
    func firstButtonClicked(){
       print("First Button Clicked")
    }
    

提交回复
热议问题