Make a UIButton programmatically in Swift

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

    Yeah in simulator. Some times it wont recognise the selector there is a bug it seems. Even i faced not for your code , then i just changed the action name (selector). It works

    let buttonPuzzle:UIButton = UIButton(frame: CGRectMake(100, 400, 100, 50))
    buttonPuzzle.backgroundColor = UIColor.greenColor()
    buttonPuzzle.setTitle("Puzzle", forState: UIControlState.Normal)
    buttonPuzzle.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
    buttonPuzzle.tag = 22;
    self.view.addSubview(buttonPuzzle)
    

    An example selector function is here:

    func buttonAction(sender:UIButton!) {
        var btnsendtag:UIButton = sender
        if btnsendtag.tag == 22 {            
            //println("Button tapped tag 22")
        }
    }
    
    0 讨论(0)
  • 2020-11-27 10:39

    Swift 4

        private func createButton {
            let sayButtonT = UIButton(type: .custom)
            sayButtonT.addTarget(self, action: #selector(sayAction(_:)), for: .touchUpInside)
        }
    
        @objc private func sayAction(_ sender: UIButton?) {
    
        }
    
    0 讨论(0)
  • 2020-11-27 10:41

    You're just missing the colon at the end of the selector name. Since pressed takes a parameter the colon must be there. Also your pressed function shouldn't be nested inside viewDidLoad.

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let myFirstLabel = UILabel()
        let myFirstButton = UIButton()
        myFirstLabel.text = "I made a label on the screen #toogood4you"
        myFirstLabel.font = UIFont(name: "MarkerFelt-Thin", size: 45)
        myFirstLabel.textColor = UIColor.redColor()
        myFirstLabel.textAlignment = .Center
        myFirstLabel.numberOfLines = 5
        myFirstLabel.frame = CGRectMake(15, 54, 300, 500)
        myFirstButton.setTitle("✸", forState: .Normal)
        myFirstButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
        myFirstButton.frame = CGRectMake(15, -50, 300, 500)
        myFirstButton.addTarget(self, action: #selector(myClass.pressed(_:)), forControlEvents: .TouchUpInside)
        self.view.addSubview(myFirstLabel)
        self.view.addSubview(myFirstButton)
    }
    
    @objc func pressed(sender: UIButton!) {
        var alertView = UIAlertView()
        alertView.addButtonWithTitle("Ok")
        alertView.title = "title"
        alertView.message = "message"
        alertView.show()
    }
    

    EDIT: Updated to reflect best practices in Swift 2.2. #selector() should be used rather than a literal string which is deprecated.

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

    UIButton with constraints in iOS 9.1/Xcode 7.1.1/Swift 2.1:

    import UIKit
    import MapKit
    
    class MapViewController: UIViewController {  
    
        override func loadView() {
            mapView = MKMapView()  //Create a view...
            view = mapView         //assign it to the ViewController's (inherited) view property.
                                   //Equivalent to self.view = mapView
    
            myButton = UIButton(type: .RoundedRect)  //RoundedRect is an alias for System (tested by printing out their rawValue's)
            //myButton.frame = CGRect(x:50, y:500, width:70, height:50)  //Doesn't seem to be necessary when using constraints.
            myButton.setTitle("Current\nLocation", forState: .Normal)
            myButton.titleLabel?.lineBreakMode = .ByWordWrapping  //If newline in title, split title onto multiple lines
            myButton.titleLabel?.textAlignment = .Center
            myButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
            myButton.layer.cornerRadius = 6   //For some reason, a button with type RoundedRect has square corners
            myButton.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.5) //Make the color partially transparent
            //Attempt to add padding around text. Shrunk the frame when I tried it.  Negative values had no effect.
            //myButton.titleEdgeInsets = UIEdgeInsetsMake(-10,-10,-10,-10)
            myButton.contentEdgeInsets = UIEdgeInsetsMake(5,5,5,5)  //Add padding around text.
    
            myButton.addTarget(self, action: "getCurrentLocation:", forControlEvents: .TouchUpInside)
            mapView.addSubview(myButton)
    
            //Button Constraints:
            myButton.translatesAutoresizingMaskIntoConstraints = false //***
            //bottomLayoutGuide(for tab bar) and topLayoutGuide(for status bar) are properties of the ViewController
            //To anchor above the tab bar on the bottom of the screen:
            let bottomButtonConstraint = myButton.bottomAnchor.constraintEqualToAnchor(bottomLayoutGuide.topAnchor, constant: -20) //Implied call of self.bottomLayoutGuide. Anchor 20 points **above** the top of the tab bar.
            //To anchor to the blue guide line that is inset from the left 
            //edge of the screen in InterfaceBuilder:
            let margins = view.layoutMarginsGuide  //Now the guide is a property of the View.
            let leadingButtonConstraint = myButton.leadingAnchor.constraintEqualToAnchor(margins.leadingAnchor)
    
            bottomButtonConstraint.active = true
            leadingButtonConstraint.active = true
        }
    
    
        func getCurrentLocation(sender: UIButton) {
            print("Current Location button clicked!")
        }
    

    The button is anchored to the bottom left corner, above the tab bar.

    0 讨论(0)
  • Swift 2.2 Xcode 7.3

    Since Objective-C String Literals are deprecated now for button callback methods

    let button:UIButton = UIButton(frame: CGRectMake(100, 400, 100, 50))
    button.backgroundColor = UIColor.blackColor()
    button.setTitle("Button", forState: UIControlState.Normal)
    button.addTarget(self, action:#selector(self.buttonClicked), forControlEvents: .TouchUpInside)
    self.view.addSubview(button)
    
    func buttonClicked() {
         print("Button Clicked")
    }
    

    Swift 3 Xcode 8

    let button:UIButton = UIButton(frame: CGRect(x: 100, y: 400, width: 100, height: 50))
    button.backgroundColor = .black
    button.setTitle("Button", for: .normal)
    button.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
    self.view.addSubview(button)
    
    func buttonClicked() {
        print("Button Clicked")
    }
    

    Swift 4 Xcode 9

    let button:UIButton = UIButton(frame: CGRect(x: 100, y: 400, width: 100, height: 50))
    button.backgroundColor = .black
    button.setTitle("Button", for: .normal)
    button.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
    self.view.addSubview(button)
    
    @objc func buttonClicked() {
        print("Button Clicked")
    }
    
    0 讨论(0)
  • 2020-11-27 10:42

    Swift 4/5

    let button = UIButton(frame: CGRect(x: 20, y: 20, width: 200, height: 60))
     button.setTitle("Email", for: .normal)
     button.backgroundColor = .white
     button.setTitleColor(UIColor.black, for: .normal)
     button.addTarget(self, action: #selector(self.buttonTapped), for: .touchUpInside)
     myView.addSubview(button)
    
    
    
    @objc func buttonTapped(sender : UIButton) {
                    //Write button action here
                }
    
    0 讨论(0)
提交回复
热议问题