Make a UIButton programmatically in Swift

后端 未结 19 1856
死守一世寂寞
死守一世寂寞 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 10:30

    You should be able to create a customize UI button programmatically by accessing the titleLabel property of UIButton.

    Per Class Reference in Swift: Regarding the titleLabel property, it says that "although this property is read-only, its own properties are read/write. Use these properties primarily to configure the text of the button."

    In Swift, you can directly modify the properties of titleLabel like such:

    let myFirstButton = UIButton()
    myFirstButton.titleLabel!.text = "I made a label on the screen #toogood4you"
    myFirstButton.titleLabel!.font = UIFont(name: "MarkerFelt-Thin", size: 45)
    myFirstButton.titleLabel!.textColor = UIColor.red
    myFirstButton.titleLabel!.textAlignment = .center
    myFirstButton.titleLabel!.numberOfLines = 5
    myFirstButton.titleLabel!.frame = CGRect(x: 15, y: 54, width: 300, height: 500)
    

    Edit

    Swift 3.1 Syntax

提交回复
热议问题