Make a UIButton programmatically in Swift

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

    Swift "Button factory" extension for UIButton (and while we're at it) also for UILabel like so:

    extension UILabel
    {
    // A simple UILabel factory function
    // returns instance of itself configured with the given parameters
    
    // use example (in a UIView or any other class that inherits from UIView):
    
    //   addSubview(   UILabel().make(     x: 0, y: 0, w: 100, h: 30,
    //                                   txt: "Hello World!",
    //                                 align: .center,
    //                                   fnt: aUIFont,
    //                              fntColor: UIColor.red)                 )
    //
    
    func make(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat,
              txt: String,
              align: NSTextAlignment,
              fnt: UIFont,
              fntColor: UIColor)-> UILabel
    {
        frame = CGRect(x: x, y: y, width: w, height: h)
        adjustsFontSizeToFitWidth = true
        textAlignment = align
        text = txt
        textColor = fntColor
        font = fnt
        return self
    }
    // Of course, you can make more advanced factory functions etc.
    // Also one could subclass UILabel, but this seems to be a     convenient case for an extension.
    }
    
    
    extension UIButton
    {
    // UIButton factory returns instance of UIButton
    //usage example:
    
    // addSubview(UIButton().make(x: btnx, y:100, w: btnw, h: btnh,
    // title: "play", backColor: .red,
    // target: self,
    // touchDown: #selector(play), touchUp: #selector(stopPlay)))
    
    
    func make(   x: CGFloat,y: CGFloat,
                 w: CGFloat,h: CGFloat,
                      title: String, backColor: UIColor,
                      target: UIView,
                      touchDown:  Selector,
                      touchUp:    Selector ) -> UIButton
    {
        frame = CGRect(x: x, y: y, width: w, height: h)
        backgroundColor = backColor
        setTitle(title, for: .normal)
        addTarget(target, action: touchDown, for: .touchDown)
        addTarget(target, action: touchUp  , for: .touchUpInside)
        addTarget(target, action: touchUp  , for: .touchUpOutside)
    
        return self
    }
    }
    

    Tested in Swift in Xcode Version 9.2 (9C40b) Swift 4.x

提交回复
热议问题