Make a UIButton programmatically in Swift

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

    Swift 3: You can create a UIButton programmatically

    either inside a methods scope for example in ViewDidLoad() Be sure to add constraints to the button, otherwise you wont see it

    let button = UIButton()
    button.translatesAutoresizingMaskIntoConstraints = false
    button.target(forAction: #selector(buttonAction), withSender: self)
    //button.backgroundColor etc
    
    view.addSubview(button)
    
    @objc func buttonAction() {
       //some Action
    }
    

    or outside your scope as global variable to access it from anywhere in your module

    let button: UIButton = {
       let b = UIButton()
       b.translatesAutoresizingMaskIntoConstraints = false
       //b.backgroundColor etc
       return b
    }()
    

    and then you setup the constraints

    func setupButtonView() {
       view.addSubview(button)
       button.widthAnchor.constraint(equalToConstant: 40).isActive = true
       button.heightAnchor.constraint(equalToConstant: 40).isActive = true
       // etc
    
    }
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-27 10:30

    Using this in Objective-C

    UIButton *testButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [testButton setTitle:@"Go to here" forState:UIControlStateNormal];
    testButton.frame = CGRectMake(20, 20, 150, 150);    
    [self.view addSubview:testButton];
    

    Using this in Latest Swift

    let testButton   = UIButton(type: UIButtonType.system) as UIButton
    testButton.frame = CGRectMake(160, 160, 80, 20)
    testButton.backgroundColor = UIColor.green
    testButton.setTitle("Button testing:- ", forState: UIControlState.normal)
    self.view.addSubview(testButton)
    
    0 讨论(0)
  • 2020-11-27 10:32

    If you go into the Main storyboard part, and in the bottom right go to the circle with a square, and use a blank button. Then in the code use @IBAction with it to get it wired in. Then you can make a @IBAction function with it.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 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")
    }
    
    0 讨论(0)
提交回复
热议问题