How do I create a basic UIButton programmatically?

后端 未结 30 1374
清歌不尽
清歌不尽 2020-11-22 14:41

How can I create a basic UIButton programmatically? For example in my view controller, when executing the viewDidLoad method, three UIButton<

30条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 15:08

    In Swift 5 and Xcode 10.2

    Basically we have two types of buttons.

    1) System type button

    2) Custom type button (In custom type button we can set background image for button)

    And these two types of buttons has few control states https://developer.apple.com/documentation/uikit/uicontrol/state

    Important states are

    1) Normal state

    2) Selected state

    3) Highlighted state

    4) Disabled state etc...

    //For system type button
    let button = UIButton(type: .system)
    button.frame = CGRect(x: 100, y: 250, width: 100, height: 50)
    //  button.backgroundColor = .blue
    button.setTitle("Button", for: .normal)
    button.setTitleColor(.white, for: .normal)
    button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 13.0)
    button.titleLabel?.textAlignment = .center//Text alighment center
    button.titleLabel?.numberOfLines = 0//To display multiple lines in UIButton
    button.titleLabel?.lineBreakMode = .byWordWrapping//By word wrapping
    button.tag = 1//To assign tag value
    button.btnProperties()//Call UIButton properties from extension function
    button.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
    self.view.addSubview(button)
    
    //For custom type button (add image to your button)
    let button2 = UIButton(type: .custom)
    button2.frame = CGRect(x: 100, y: 400, width: 100, height: 50)
    //        button2.backgroundColor = .blue
    button2.setImage(UIImage.init(named: "img.png"), for: .normal)
    button2.tag = 2
    button2.btnProperties()//Call UIButton properties from extension function
    button2.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
    self.view.addSubview(button2)
    
    @objc func buttonClicked(sender:UIButton) {
        print("Button \(sender.tag) clicked")
    }
    
    //You can add UIButton properties using extension
    extension UIButton {
        func btnProperties() {
            layer.cornerRadius = 10//Set button corner radious
            clipsToBounds = true
            backgroundColor = .blue//Set background colour
            //titleLabel?.textAlignment = .center//add properties like this
        }
    }
    

提交回复
热议问题