美文网首页
在 UIButton 的子类中如何设置 UIButtonType

在 UIButton 的子类中如何设置 UIButtonType

作者: Desmond_ | 来源:发表于2018-04-17 15:47 被阅读15次

    UIButtonType 这是个只读属性,意味着你不能通过以下语句来设置它:


    AF559AC4-5385-4EB2-B03D-BBAEFB42F415.png

    当你创建一个 UIButton 对象的时候,如果没有指定 UIButtonType,那么默认将被设置成 .custom。那如何在子类中设置呢?可以用如下方法:

    import UIKit
    
    class customButton: UIButton {
        
        static func createButton() -> customButton {
            
            let button = customButton(type: .system)
            button.setTitle("我是按钮", for: .normal)
            
            return button
        }
    }
    

    然后这么调用:

    let button = customButton.createBackButton()
    

    另外,不通过创建子类也能实现(工厂方法):

    extension UIButton {
        static func createButton() -> UIButton {
            let button = UIButton(type: .system)
            button.setTitle("我是按钮", for: .normal)
            return button
        }
    }
    

    调用:

    self.button = UIButton.createButton()
    

    相关文章

      网友评论

          本文标题:在 UIButton 的子类中如何设置 UIButtonType

          本文链接:https://www.haomeiwen.com/subject/bvfpkftx.html