How to create a button programmatically?











up vote
218
down vote

favorite
67












How do I programmatically create graphical elements (like a UIButton) in Swift? I tried to create and add button into a view, but wasn't able to.










share|improve this question




























    up vote
    218
    down vote

    favorite
    67












    How do I programmatically create graphical elements (like a UIButton) in Swift? I tried to create and add button into a view, but wasn't able to.










    share|improve this question


























      up vote
      218
      down vote

      favorite
      67









      up vote
      218
      down vote

      favorite
      67






      67





      How do I programmatically create graphical elements (like a UIButton) in Swift? I tried to create and add button into a view, but wasn't able to.










      share|improve this question















      How do I programmatically create graphical elements (like a UIButton) in Swift? I tried to create and add button into a view, but wasn't able to.







      ios swift uibutton






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 22 at 8:56









      Shruti Thombre

      586419




      586419










      asked Jun 4 '14 at 6:18









      val_lek

      1,26521010




      1,26521010
























          21 Answers
          21






          active

          oldest

          votes

















          up vote
          358
          down vote













          Here is a complete solution to add a UIButton programmatically with the targetAction.
          Swift 2.2



          override func viewDidLoad() {
          super.viewDidLoad()

          let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
          button.backgroundColor = .greenColor()
          button.setTitle("Test Button", forState: .Normal)
          button.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)

          self.view.addSubview(button)
          }

          func buttonAction(sender: UIButton!) {
          print("Button tapped")
          }


          It is probably better to use NSLayoutConstraint rather than frame to correctly place the button for each iPhone screen.



          Updated code to Swift 3.1:



          override func viewDidLoad() {
          super.viewDidLoad()

          let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
          button.backgroundColor = .green
          button.setTitle("Test Button", for: .normal)
          button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

          self.view.addSubview(button)
          }

          func buttonAction(sender: UIButton!) {
          print("Button tapped")
          }


          Updated code to Swift 4.2:



          override func viewDidLoad() {
          super.viewDidLoad()

          let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
          button.backgroundColor = .green
          button.setTitle("Test Button", for: .normal)
          button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

          self.view.addSubview(button)
          }

          @objc func buttonAction(sender: UIButton!) {
          print("Button tapped")
          }


          The above still works if func buttonAction is declared private or internal.






          share|improve this answer



















          • 3




            and don't forget that your target class should be derived from NSObject
            – Alexey Globchastyy
            Jul 20 '14 at 7:54






          • 6




            and dont forget that the function that is your action cannot be private
            – Pablo Zbigy Jablonski
            Nov 20 '14 at 23:00






          • 2




            It's weird that they decided to do action with string instead of using a function (with strings it's even more unsafe than selectors!). Backwards compatibility with Obj-C probably :(
            – Ixx
            Dec 8 '14 at 21:26












          • Is there any way to change a buttons corner radius?
            – DeveloperACE
            Jan 27 '15 at 21:05






          • 3




            As of Swift 1.2 downcasts can no longer be done with "as", they must be “forced failable” with "as!".
            – TenaciousJay
            May 1 '15 at 16:38


















          up vote
          95
          down vote













          You can add UIButton,UIlable and UITextfield programmatically in this way.



          UIButton code



          // var button   = UIButton.buttonWithType(UIButtonType.System) as UIButton
          let button = UIButton(type: .System) // let preferred over var here
          button.frame = CGRectMake(100, 100, 100, 50)
          button.backgroundColor = UIColor.greenColor()
          button.setTitle("Button", forState: UIControlState.Normal)
          button.addTarget(self, action: "Action:", forControlEvents: UIControlEvents.TouchUpInside)
          self.view.addSubview(button)


          UILabel Code



          var label: UILabel = UILabel()
          label.frame = CGRectMake(50, 50, 200, 21)
          label.backgroundColor = UIColor.blackColor()
          label.textColor = UIColor.whiteColor()
          label.textAlignment = NSTextAlignment.Center
          label.text = "test label"
          self.view.addSubview(label)


          UITextField code



          var txtField: UITextField = UITextField()
          txtField.frame = CGRectMake(50, 70, 200, 30)
          txtField.backgroundColor = UIColor.grayColor()
          self.view.addSubview(txtField)


          Hope this is helpful for you.






          share|improve this answer























          • so, why do you need the "as" operator in the first line of code you shared before UIButton...?
            – zumzum
            Jun 13 '14 at 22:32










          • buttonWithType returns type AnyObject, so you need to cast it as a UIButton
            – Chris C
            Sep 19 '14 at 13:07






          • 1




            @ElgsQianChen You can use this code according to your requirement. for example you want to add a UIButton when view appear you add the code in viewWillAppear.
            – Akhtar
            Sep 25 '14 at 12:06








          • 1




            As of Swift 1.2 downcasts can no longer be done with "as", they must be “forced failable” with "as!".
            – TenaciousJay
            May 1 '15 at 16:38










          • For people who run into Objective C String literals deprecated warnings Correct answer is here: stackoverflow.com/a/36308587/968848
            – n.by.n
            Mar 30 '16 at 12:27


















          up vote
          54
          down vote













          For Swift 3



          let button = UIButton()
          button.frame = CGRect(x: self.view.frame.size.width - 60, y: 60, width: 50, height: 50)
          button.backgroundColor = UIColor.red
          button.setTitle("Name your Button ", for: .normal)
          button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
          self.view.addSubview(button)

          func buttonAction(sender: UIButton!) {
          print("Button tapped")
          }


          For Swift 4



           let button = UIButton()
          button.frame = CGRect(x: self.view.frame.size.width - 60, y: 60, width: 50, height: 50)
          button.backgroundColor = UIColor.red
          button.setTitle("Name your Button ", for: .normal)
          button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
          self.view.addSubview(button)

          @objc func buttonAction(sender: UIButton!) {
          print("Button tapped")
          }





          share|improve this answer























          • button.frame = (frame: CGRect(x: self.view.frame.size.width - 60, y: 20, width: 50, height: 50)) should be button.frame = CGRect(x: self.view.frame.size.width - 60, y: 20, width: 50, height: 50)
            – J.C
            Mar 30 '17 at 15:40






          • 2




            In Swift 4 before "func" need to add "@objc".
            – Ruslan Leshchenko
            Mar 19 at 8:10


















          up vote
          29
          down vote













          Swift 3



          let btn = UIButton(type: .custom) as UIButton
          btn.backgroundColor = .blue
          btn.setTitle("Button", for: .normal)
          btn.frame = CGRect(x: 100, y: 100, width: 200, height: 100)
          btn.addTarget(self, action: #selector(clickMe), for: .touchUpInside)
          self.view.addSubview(btn)

          func clickMe(sender:UIButton!) {
          print("Button Clicked")
          }


          Output



          enter image description here






          share|improve this answer























          • Thanks, m8! Starting up with Swift today so everything is kind of strange (:
            – Felipe
            Oct 27 '15 at 18:13


















          up vote
          16
          down vote













          How to do this using Swift 3.0.



          func createButton() {
          let button = UIButton(type: .system)
          button.frame = CGRect(x: 100.0, y: 100.0, width: 100.0, height: 100.0)
          button.setTitle(NSLocalizedString("Button", comment: "Button"), for: .normal)
          button.backgroundColor = .green
          button.addTarget(self, action: #selector(buttonAction(sender:)), for: .touchUpInside)
          view.addSubview(button)
          }

          @objc func buttonAction(sender: UIButton) {
          print("Button pushed")
          }





          share|improve this answer




























            up vote
            13
            down vote













             var sampleButton:UIButton?

            override func viewDidLoad() {
            super.viewDidLoad()

            }
            override func viewDidAppear(animated: Bool) {

            sampleButton = UIButton(type: .RoundedRect)
            //sampleButton.frame = CGRect(x:50, y:500, width:70, height:50)

            sampleButton!.setTitle("Sample n UI Button", forState: .Normal)
            sampleButton!.titleLabel?.lineBreakMode = .ByWordWrapping
            sampleButton!.titleLabel?.textAlignment = .Center
            sampleButton!.setTitleColor(UIColor.whiteColor(), forState: .Normal)
            sampleButton!.layer.cornerRadius = 6
            sampleButton!.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.6)
            sampleButton?.tintColor = UIColor.brownColor()


            //Add padding around text
            sampleButton!.titleEdgeInsets = UIEdgeInsetsMake(-10,-10,-10,-10)
            sampleButton!.contentEdgeInsets = UIEdgeInsetsMake(5,5,5,5)

            //Action set up
            sampleButton!.addTarget(self, action: "sampleButtonClicked", forControlEvents: .TouchUpInside)
            self.view.addSubview(sampleButton!)


            //Button Constraints:
            sampleButton!.translatesAutoresizingMaskIntoConstraints = false

            //To anchor above the tab bar on the bottom of the screen:
            let bottomButtonConstraint = sampleButton!.bottomAnchor.constraintEqualToAnchor(bottomLayoutGuide.topAnchor, constant: -20)

            //edge of the screen in InterfaceBuilder:
            let margins = view.layoutMarginsGuide
            let leadingButtonConstraint = sampleButton!.leadingAnchor.constraintEqualToAnchor(margins.leadingAnchor)

            bottomButtonConstraint.active = true
            leadingButtonConstraint.active = true


            }
            func sampleButtonClicked(){

            print("sample Button Clicked")

            }





            share|improve this answer




























              up vote
              13
              down vote













              The API hasn't changed - only the syntax has. You can make a UIButton and add it like this:



              var button = UIButton(frame: CGRectMake(0, 0, 50, 50))
              self.view.addSubview(button) // assuming you're in a view controller





              share|improve this answer






























                up vote
                6
                down vote













                Add this code in viewDidLoad

                //add Button



                            var button=UIButton(frame: CGRectMake(150, 240, 75, 30))
                button.setTitle("Next", forState: UIControlState.Normal)
                button.addTarget(self, action: "buttonTapAction:", forControlEvents: UIControlEvents.TouchUpInside)
                button.backgroundColor = UIColor.greenColor()
                self.view.addSubview(button)


                Write this function outside it,this will call when you tap on the button



                func buttonTapAction(sender:UIButton!)
                {
                println("Button is working")
                }





                share|improve this answer




























                  up vote
                  6
                  down vote













                  In Swift 2 and iOS 9.2.1



                  var button: UIButton = UIButton(type: UIButtonType.Custom) as UIButton
                  self.button.frame = CGRectMake(130, 70, 60, 20)
                  self.button.setTitle("custom button", forState: UIControlState.Normal)
                  self.button.addTarget(self, action:"buttonActionFuncName", forControlEvents: UIControlEvents.TouchUpInside)
                  self.button.setTitleColor(UIColor.blackColor(), forState: .Normal)
                  self.button.layer.borderColor = UIColor.blackColor().CGColor
                  self.button.titleLabel?.font = UIFont(name: "Helvetica-Bold", size: 13)
                  self.view.addSubview(self.button)





                  share|improve this answer






























                    up vote
                    6
                    down vote













                    You can create like this and you can add action also like this....



                    import UIKit

                    let myButton = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50))

                    init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!)
                    { super.init(nibName: nibName, bundle: nibBundle)
                    myButton.targetForAction("tappedButton:", withSender: self)
                    }

                    func tappedButton(sender: UIButton!)
                    {
                    println("tapped button")
                    }





                    share|improve this answer























                    • sorry, but the compiler sent error in line - self.view.addSubview(view: myButton). Error is next: "Extraneous argument label 'view:' in call"
                      – val_lek
                      Jun 4 '14 at 7:26










                    • Please remove this line self.view.addSubview(view: myButton) For more info see my edited answer.
                      – Dharmbir Singh
                      Jun 4 '14 at 7:26












                    • Thank you, but how I can add this button on self.view?
                      – val_lek
                      Jun 4 '14 at 7:31


















                    up vote
                    4
                    down vote













                    It is possible. You do everything pretty much the same way except use the swift syntax. For example you could make a UIButton in code like this:



                     var button: UIButton = UIButton(frame: CGRectMake(0, 0, 100, 100))





                    share|improve this answer




























                      up vote
                      3
                      down vote













                      For create UIButton from storyboard:
                      1 - Drag UIButton object from Object Library to ViewController in storyboard file
                      2 - Show Assistant editor
                      3 - Drag with right click from UIButton create above into your class. The result is the following:



                      @IBAction func buttonActionFromStoryboard(sender: UIButton)
                      {
                      println("Button Action From Storyboard")
                      }


                      For create UIButton programmatically:
                      1- Write into "override func viewDidLoad()":



                              let uiButton    = UIButton.buttonWithType(UIButtonType.System) as UIButton
                      uiButton.frame = CGRectMake(16, 116, 288, 30)
                      uiButton.setTitle("Second", forState: UIControlState.Normal);
                      uiButton.addTarget(self, action: "buttonActionFromCode:", forControlEvents: UIControlEvents.TouchUpInside)
                      self.view.addSubview(uiButton)


                      2- add the IBAction func:



                      @IBAction func buttonActionFromCode(sender:UIButton)
                      {
                      println("Button Action From Code")
                      }





                      share|improve this answer





















                      • As of Swift 1.2 downcasts can no longer be done with "as", they must be “forced failable” with "as!".
                        – TenaciousJay
                        May 1 '15 at 16:38


















                      up vote
                      3
                      down vote













                                  let myFirstButton = UIButton()
                      myFirstButton.setTitle("Software Button", forState: .Normal)
                      myFirstButton.setTitleColor(UIColor.redColor(), forState: .Normal)
                      myFirstButton.frame = CGRectMake(100, 300, 150, 50)
                      myFirstButton.backgroundColor = UIColor.purpleColor()
                      myFirstButton.layer.cornerRadius = 14
                      myFirstButton.addTarget(self, action: "pressed:", forControlEvents: .TouchUpInside)
                      self.view.addSubview(myFirstButton)
                      myFirstButton.hidden=true
                      nameText.delegate = self


                      func pressed(sender: UIButton!) {
                      var alertView = UIAlertView()
                      alertView.addButtonWithTitle("Ok")
                      alertView.title = "title"
                      alertView.message = "message"
                      alertView.show();
                      }





                      share|improve this answer




























                        up vote
                        3
                        down vote













                        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)


                        Selector Function is Here:



                        func buttonAction(sender:UIButton!)
                        {

                        var btnsendtag:UIButton = sender
                        if btnsendtag.tag == 22 {
                        //println("Button tapped tag 22")
                        }
                        }





                        share|improve this answer























                        • Seems like I'm running into the same issue. I initially created the button a IBAction in the storyboard, but I get "unrecognized selector sent to instance", then I delete the IBAction created that way and tried using .addTarget, they both lead to the same error.
                          – RayInNoIL
                          Aug 30 '15 at 14:34










                        • What worked for me was to delete all the IBOutlet and IBAction code in the .swift file and all the connections in InterfaceBuilder. Then re-creating everything.
                          – RayInNoIL
                          Aug 30 '15 at 16:42


















                        up vote
                        1
                        down vote














                        This works for me very well, #DynamicButtonEvent #IOS #Swift #Xcode




                        func setupButtonMap(){
                        let mapButton = UIButton(type: .system)
                        mapButton.setImage(#imageLiteral(resourceName: "CreateTrip").withRenderingMode(.alwaysOriginal), for: .normal)
                        mapButton.frame = CGRect(x: 0, y: 0, width: 34, height: 34)
                        mapButton.contentMode = .scaleAspectFit
                        mapButton.backgroundColor = UIColor.clear
                        mapButton.addTarget(self, action: #selector(ViewController.btnOpenMap(_:)), for: .touchUpInside)
                        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: mapButton)
                        }
                        @IBAction func btnOpenMap(_ sender: Any?) {
                        print("Successful")
                        }





                        share|improve this answer




























                          up vote
                          0
                          down vote













                          Swift: Ui Button create programmatically



                          let myButton = UIButton()

                          myButton.titleLabel!.frame = CGRectMake(15, 54, 300, 500)
                          myButton.titleLabel!.text = "Button Label"
                          myButton.titleLabel!.textColor = UIColor.redColor()
                          myButton.titleLabel!.textAlignment = .Center
                          self.view.addSubview(myButton)





                          share|improve this answer






























                            up vote
                            0
                            down vote













                            Uilabel code 

                            var label: UILabel = UILabel()
                            label.frame = CGRectMake(50, 50, 200, 21)
                            label.backgroundColor = UIColor.blackColor()
                            label.textColor = UIColor.whiteColor()
                            label.textAlignment = NSTextAlignment.Center
                            label.text = "test label"
                            self.view.addSubview(label)





                            share|improve this answer

















                            • 2




                              It is always advised to add some explanation to your code
                              – Bowdzone
                              May 26 '15 at 10:30


















                            up vote
                            0
                            down vote













                                // UILabel:
                            let label = UILabel()
                            label.frame = CGRectMake(35, 100, 250, 30)
                            label.textColor = UIColor.blackColor()
                            label.textAlignment = NSTextAlignment.Center
                            label.text = "Hello World"
                            self.view.addSubview(label)

                            // UIButton:
                            let btn: UIButton = UIButton(type: UIButtonType.Custom) as UIButton
                            btn.frame = CGRectMake(130, 70, 60, 20)
                            btn.setTitle("Click", forState: UIControlState.Normal)
                            btn.setTitleColor(UIColor.blackColor(), forState: .Normal)
                            btn.addTarget(self, action:Selector("clickAction"), forControlEvents: UIControlEvents.TouchUpInside)
                            view.addSubview(btn)


                            // Button Action:
                            @IBAction func clickAction(sender:AnyObject)
                            {
                            print("Click Action")
                            }





                            share|improve this answer




























                              up vote
                              0
                              down vote













                              Step 1: Make a new project



                              enter image description here



                              Step 2: in ViewController.swift



                              import UIKit

                              class ViewController: UIViewController {

                              override func viewDidLoad() {
                              super.viewDidLoad()

                              // CODE
                              let btn = UIButton(type: UIButtonType.System) as UIButton
                              btn.backgroundColor = UIColor.blueColor()
                              btn.setTitle("CALL TPT AGENT", forState: UIControlState.Normal)
                              btn.frame = CGRectMake(100, 100, 200, 100)
                              btn.addTarget(self, action: "clickMe:", forControlEvents: UIControlEvents.TouchUpInside)
                              self.view.addSubview(btn)

                              }

                              func clickMe(sender:UIButton!) {
                              print("CALL")
                              }

                              override func didReceiveMemoryWarning() {
                              super.didReceiveMemoryWarning()
                              // Dispose of any resources that can be recreated.
                              }


                              }





                              share|improve this answer




























                                up vote
                                0
                                down vote













                                enter image description here



                                 func viewDidLoad(){
                                saveActionButton = UIButton(frame: CGRect(x: self.view.frame.size.width - 60, y: 0, width: 50, height: 50))
                                self.saveActionButton.backgroundColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 0.7)
                                saveActionButton.addTarget(self, action: #selector(doneAction), for: .touchUpInside)
                                self.saveActionButton.setTitle("Done", for: .normal)
                                self.saveActionButton.layer.cornerRadius = self.saveActionButton.frame.size.width / 2
                                self.saveActionButton.layer.borderColor = UIColor.darkGray.cgColor
                                self.saveActionButton.layer.borderWidth = 1
                                self.saveActionButton.center.y = self.view.frame.size.height - 80
                                self.view.addSubview(saveActionButton)
                                }

                                func doneAction(){
                                print("Write your own logic")
                                }





                                share|improve this answer






























                                  up vote
                                  -1
                                  down vote













                                  override func viewDidLoad() {

                                  super.viewDidLoad()
                                  // Do any additional setup after loading the view, typically from a nib.

                                  var imageView = UIImageView(frame: CGRectMake(100, 150, 150, 150));
                                  var image = UIImage(named: "BattleMapSplashScreen.png");
                                  imageView.image = image;
                                  self.view.addSubview(imageView);

                                  }





                                  share|improve this answer























                                    Your Answer






                                    StackExchange.ifUsing("editor", function () {
                                    StackExchange.using("externalEditor", function () {
                                    StackExchange.using("snippets", function () {
                                    StackExchange.snippets.init();
                                    });
                                    });
                                    }, "code-snippets");

                                    StackExchange.ready(function() {
                                    var channelOptions = {
                                    tags: "".split(" "),
                                    id: "1"
                                    };
                                    initTagRenderer("".split(" "), "".split(" "), channelOptions);

                                    StackExchange.using("externalEditor", function() {
                                    // Have to fire editor after snippets, if snippets enabled
                                    if (StackExchange.settings.snippets.snippetsEnabled) {
                                    StackExchange.using("snippets", function() {
                                    createEditor();
                                    });
                                    }
                                    else {
                                    createEditor();
                                    }
                                    });

                                    function createEditor() {
                                    StackExchange.prepareEditor({
                                    heartbeatType: 'answer',
                                    convertImagesToLinks: true,
                                    noModals: true,
                                    showLowRepImageUploadWarning: true,
                                    reputationToPostImages: 10,
                                    bindNavPrevention: true,
                                    postfix: "",
                                    imageUploader: {
                                    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                                    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                                    allowUrls: true
                                    },
                                    onDemand: true,
                                    discardSelector: ".discard-answer"
                                    ,immediatelyShowMarkdownHelp:true
                                    });


                                    }
                                    });














                                    draft saved

                                    draft discarded


















                                    StackExchange.ready(
                                    function () {
                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f24030348%2fhow-to-create-a-button-programmatically%23new-answer', 'question_page');
                                    }
                                    );

                                    Post as a guest















                                    Required, but never shown

























                                    21 Answers
                                    21






                                    active

                                    oldest

                                    votes








                                    21 Answers
                                    21






                                    active

                                    oldest

                                    votes









                                    active

                                    oldest

                                    votes






                                    active

                                    oldest

                                    votes








                                    up vote
                                    358
                                    down vote













                                    Here is a complete solution to add a UIButton programmatically with the targetAction.
                                    Swift 2.2



                                    override func viewDidLoad() {
                                    super.viewDidLoad()

                                    let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
                                    button.backgroundColor = .greenColor()
                                    button.setTitle("Test Button", forState: .Normal)
                                    button.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)

                                    self.view.addSubview(button)
                                    }

                                    func buttonAction(sender: UIButton!) {
                                    print("Button tapped")
                                    }


                                    It is probably better to use NSLayoutConstraint rather than frame to correctly place the button for each iPhone screen.



                                    Updated code to Swift 3.1:



                                    override func viewDidLoad() {
                                    super.viewDidLoad()

                                    let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
                                    button.backgroundColor = .green
                                    button.setTitle("Test Button", for: .normal)
                                    button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

                                    self.view.addSubview(button)
                                    }

                                    func buttonAction(sender: UIButton!) {
                                    print("Button tapped")
                                    }


                                    Updated code to Swift 4.2:



                                    override func viewDidLoad() {
                                    super.viewDidLoad()

                                    let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
                                    button.backgroundColor = .green
                                    button.setTitle("Test Button", for: .normal)
                                    button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

                                    self.view.addSubview(button)
                                    }

                                    @objc func buttonAction(sender: UIButton!) {
                                    print("Button tapped")
                                    }


                                    The above still works if func buttonAction is declared private or internal.






                                    share|improve this answer



















                                    • 3




                                      and don't forget that your target class should be derived from NSObject
                                      – Alexey Globchastyy
                                      Jul 20 '14 at 7:54






                                    • 6




                                      and dont forget that the function that is your action cannot be private
                                      – Pablo Zbigy Jablonski
                                      Nov 20 '14 at 23:00






                                    • 2




                                      It's weird that they decided to do action with string instead of using a function (with strings it's even more unsafe than selectors!). Backwards compatibility with Obj-C probably :(
                                      – Ixx
                                      Dec 8 '14 at 21:26












                                    • Is there any way to change a buttons corner radius?
                                      – DeveloperACE
                                      Jan 27 '15 at 21:05






                                    • 3




                                      As of Swift 1.2 downcasts can no longer be done with "as", they must be “forced failable” with "as!".
                                      – TenaciousJay
                                      May 1 '15 at 16:38















                                    up vote
                                    358
                                    down vote













                                    Here is a complete solution to add a UIButton programmatically with the targetAction.
                                    Swift 2.2



                                    override func viewDidLoad() {
                                    super.viewDidLoad()

                                    let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
                                    button.backgroundColor = .greenColor()
                                    button.setTitle("Test Button", forState: .Normal)
                                    button.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)

                                    self.view.addSubview(button)
                                    }

                                    func buttonAction(sender: UIButton!) {
                                    print("Button tapped")
                                    }


                                    It is probably better to use NSLayoutConstraint rather than frame to correctly place the button for each iPhone screen.



                                    Updated code to Swift 3.1:



                                    override func viewDidLoad() {
                                    super.viewDidLoad()

                                    let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
                                    button.backgroundColor = .green
                                    button.setTitle("Test Button", for: .normal)
                                    button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

                                    self.view.addSubview(button)
                                    }

                                    func buttonAction(sender: UIButton!) {
                                    print("Button tapped")
                                    }


                                    Updated code to Swift 4.2:



                                    override func viewDidLoad() {
                                    super.viewDidLoad()

                                    let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
                                    button.backgroundColor = .green
                                    button.setTitle("Test Button", for: .normal)
                                    button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

                                    self.view.addSubview(button)
                                    }

                                    @objc func buttonAction(sender: UIButton!) {
                                    print("Button tapped")
                                    }


                                    The above still works if func buttonAction is declared private or internal.






                                    share|improve this answer



















                                    • 3




                                      and don't forget that your target class should be derived from NSObject
                                      – Alexey Globchastyy
                                      Jul 20 '14 at 7:54






                                    • 6




                                      and dont forget that the function that is your action cannot be private
                                      – Pablo Zbigy Jablonski
                                      Nov 20 '14 at 23:00






                                    • 2




                                      It's weird that they decided to do action with string instead of using a function (with strings it's even more unsafe than selectors!). Backwards compatibility with Obj-C probably :(
                                      – Ixx
                                      Dec 8 '14 at 21:26












                                    • Is there any way to change a buttons corner radius?
                                      – DeveloperACE
                                      Jan 27 '15 at 21:05






                                    • 3




                                      As of Swift 1.2 downcasts can no longer be done with "as", they must be “forced failable” with "as!".
                                      – TenaciousJay
                                      May 1 '15 at 16:38













                                    up vote
                                    358
                                    down vote










                                    up vote
                                    358
                                    down vote









                                    Here is a complete solution to add a UIButton programmatically with the targetAction.
                                    Swift 2.2



                                    override func viewDidLoad() {
                                    super.viewDidLoad()

                                    let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
                                    button.backgroundColor = .greenColor()
                                    button.setTitle("Test Button", forState: .Normal)
                                    button.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)

                                    self.view.addSubview(button)
                                    }

                                    func buttonAction(sender: UIButton!) {
                                    print("Button tapped")
                                    }


                                    It is probably better to use NSLayoutConstraint rather than frame to correctly place the button for each iPhone screen.



                                    Updated code to Swift 3.1:



                                    override func viewDidLoad() {
                                    super.viewDidLoad()

                                    let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
                                    button.backgroundColor = .green
                                    button.setTitle("Test Button", for: .normal)
                                    button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

                                    self.view.addSubview(button)
                                    }

                                    func buttonAction(sender: UIButton!) {
                                    print("Button tapped")
                                    }


                                    Updated code to Swift 4.2:



                                    override func viewDidLoad() {
                                    super.viewDidLoad()

                                    let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
                                    button.backgroundColor = .green
                                    button.setTitle("Test Button", for: .normal)
                                    button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

                                    self.view.addSubview(button)
                                    }

                                    @objc func buttonAction(sender: UIButton!) {
                                    print("Button tapped")
                                    }


                                    The above still works if func buttonAction is declared private or internal.






                                    share|improve this answer














                                    Here is a complete solution to add a UIButton programmatically with the targetAction.
                                    Swift 2.2



                                    override func viewDidLoad() {
                                    super.viewDidLoad()

                                    let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
                                    button.backgroundColor = .greenColor()
                                    button.setTitle("Test Button", forState: .Normal)
                                    button.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)

                                    self.view.addSubview(button)
                                    }

                                    func buttonAction(sender: UIButton!) {
                                    print("Button tapped")
                                    }


                                    It is probably better to use NSLayoutConstraint rather than frame to correctly place the button for each iPhone screen.



                                    Updated code to Swift 3.1:



                                    override func viewDidLoad() {
                                    super.viewDidLoad()

                                    let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
                                    button.backgroundColor = .green
                                    button.setTitle("Test Button", for: .normal)
                                    button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

                                    self.view.addSubview(button)
                                    }

                                    func buttonAction(sender: UIButton!) {
                                    print("Button tapped")
                                    }


                                    Updated code to Swift 4.2:



                                    override func viewDidLoad() {
                                    super.viewDidLoad()

                                    let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
                                    button.backgroundColor = .green
                                    button.setTitle("Test Button", for: .normal)
                                    button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

                                    self.view.addSubview(button)
                                    }

                                    @objc func buttonAction(sender: UIButton!) {
                                    print("Button tapped")
                                    }


                                    The above still works if func buttonAction is declared private or internal.







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Oct 16 at 6:03









                                    Anro Swart

                                    509




                                    509










                                    answered Jun 4 '14 at 8:39









                                    Anil Varghese

                                    36.9k885106




                                    36.9k885106








                                    • 3




                                      and don't forget that your target class should be derived from NSObject
                                      – Alexey Globchastyy
                                      Jul 20 '14 at 7:54






                                    • 6




                                      and dont forget that the function that is your action cannot be private
                                      – Pablo Zbigy Jablonski
                                      Nov 20 '14 at 23:00






                                    • 2




                                      It's weird that they decided to do action with string instead of using a function (with strings it's even more unsafe than selectors!). Backwards compatibility with Obj-C probably :(
                                      – Ixx
                                      Dec 8 '14 at 21:26












                                    • Is there any way to change a buttons corner radius?
                                      – DeveloperACE
                                      Jan 27 '15 at 21:05






                                    • 3




                                      As of Swift 1.2 downcasts can no longer be done with "as", they must be “forced failable” with "as!".
                                      – TenaciousJay
                                      May 1 '15 at 16:38














                                    • 3




                                      and don't forget that your target class should be derived from NSObject
                                      – Alexey Globchastyy
                                      Jul 20 '14 at 7:54






                                    • 6




                                      and dont forget that the function that is your action cannot be private
                                      – Pablo Zbigy Jablonski
                                      Nov 20 '14 at 23:00






                                    • 2




                                      It's weird that they decided to do action with string instead of using a function (with strings it's even more unsafe than selectors!). Backwards compatibility with Obj-C probably :(
                                      – Ixx
                                      Dec 8 '14 at 21:26












                                    • Is there any way to change a buttons corner radius?
                                      – DeveloperACE
                                      Jan 27 '15 at 21:05






                                    • 3




                                      As of Swift 1.2 downcasts can no longer be done with "as", they must be “forced failable” with "as!".
                                      – TenaciousJay
                                      May 1 '15 at 16:38








                                    3




                                    3




                                    and don't forget that your target class should be derived from NSObject
                                    – Alexey Globchastyy
                                    Jul 20 '14 at 7:54




                                    and don't forget that your target class should be derived from NSObject
                                    – Alexey Globchastyy
                                    Jul 20 '14 at 7:54




                                    6




                                    6




                                    and dont forget that the function that is your action cannot be private
                                    – Pablo Zbigy Jablonski
                                    Nov 20 '14 at 23:00




                                    and dont forget that the function that is your action cannot be private
                                    – Pablo Zbigy Jablonski
                                    Nov 20 '14 at 23:00




                                    2




                                    2




                                    It's weird that they decided to do action with string instead of using a function (with strings it's even more unsafe than selectors!). Backwards compatibility with Obj-C probably :(
                                    – Ixx
                                    Dec 8 '14 at 21:26






                                    It's weird that they decided to do action with string instead of using a function (with strings it's even more unsafe than selectors!). Backwards compatibility with Obj-C probably :(
                                    – Ixx
                                    Dec 8 '14 at 21:26














                                    Is there any way to change a buttons corner radius?
                                    – DeveloperACE
                                    Jan 27 '15 at 21:05




                                    Is there any way to change a buttons corner radius?
                                    – DeveloperACE
                                    Jan 27 '15 at 21:05




                                    3




                                    3




                                    As of Swift 1.2 downcasts can no longer be done with "as", they must be “forced failable” with "as!".
                                    – TenaciousJay
                                    May 1 '15 at 16:38




                                    As of Swift 1.2 downcasts can no longer be done with "as", they must be “forced failable” with "as!".
                                    – TenaciousJay
                                    May 1 '15 at 16:38












                                    up vote
                                    95
                                    down vote













                                    You can add UIButton,UIlable and UITextfield programmatically in this way.



                                    UIButton code



                                    // var button   = UIButton.buttonWithType(UIButtonType.System) as UIButton
                                    let button = UIButton(type: .System) // let preferred over var here
                                    button.frame = CGRectMake(100, 100, 100, 50)
                                    button.backgroundColor = UIColor.greenColor()
                                    button.setTitle("Button", forState: UIControlState.Normal)
                                    button.addTarget(self, action: "Action:", forControlEvents: UIControlEvents.TouchUpInside)
                                    self.view.addSubview(button)


                                    UILabel Code



                                    var label: UILabel = UILabel()
                                    label.frame = CGRectMake(50, 50, 200, 21)
                                    label.backgroundColor = UIColor.blackColor()
                                    label.textColor = UIColor.whiteColor()
                                    label.textAlignment = NSTextAlignment.Center
                                    label.text = "test label"
                                    self.view.addSubview(label)


                                    UITextField code



                                    var txtField: UITextField = UITextField()
                                    txtField.frame = CGRectMake(50, 70, 200, 30)
                                    txtField.backgroundColor = UIColor.grayColor()
                                    self.view.addSubview(txtField)


                                    Hope this is helpful for you.






                                    share|improve this answer























                                    • so, why do you need the "as" operator in the first line of code you shared before UIButton...?
                                      – zumzum
                                      Jun 13 '14 at 22:32










                                    • buttonWithType returns type AnyObject, so you need to cast it as a UIButton
                                      – Chris C
                                      Sep 19 '14 at 13:07






                                    • 1




                                      @ElgsQianChen You can use this code according to your requirement. for example you want to add a UIButton when view appear you add the code in viewWillAppear.
                                      – Akhtar
                                      Sep 25 '14 at 12:06








                                    • 1




                                      As of Swift 1.2 downcasts can no longer be done with "as", they must be “forced failable” with "as!".
                                      – TenaciousJay
                                      May 1 '15 at 16:38










                                    • For people who run into Objective C String literals deprecated warnings Correct answer is here: stackoverflow.com/a/36308587/968848
                                      – n.by.n
                                      Mar 30 '16 at 12:27















                                    up vote
                                    95
                                    down vote













                                    You can add UIButton,UIlable and UITextfield programmatically in this way.



                                    UIButton code



                                    // var button   = UIButton.buttonWithType(UIButtonType.System) as UIButton
                                    let button = UIButton(type: .System) // let preferred over var here
                                    button.frame = CGRectMake(100, 100, 100, 50)
                                    button.backgroundColor = UIColor.greenColor()
                                    button.setTitle("Button", forState: UIControlState.Normal)
                                    button.addTarget(self, action: "Action:", forControlEvents: UIControlEvents.TouchUpInside)
                                    self.view.addSubview(button)


                                    UILabel Code



                                    var label: UILabel = UILabel()
                                    label.frame = CGRectMake(50, 50, 200, 21)
                                    label.backgroundColor = UIColor.blackColor()
                                    label.textColor = UIColor.whiteColor()
                                    label.textAlignment = NSTextAlignment.Center
                                    label.text = "test label"
                                    self.view.addSubview(label)


                                    UITextField code



                                    var txtField: UITextField = UITextField()
                                    txtField.frame = CGRectMake(50, 70, 200, 30)
                                    txtField.backgroundColor = UIColor.grayColor()
                                    self.view.addSubview(txtField)


                                    Hope this is helpful for you.






                                    share|improve this answer























                                    • so, why do you need the "as" operator in the first line of code you shared before UIButton...?
                                      – zumzum
                                      Jun 13 '14 at 22:32










                                    • buttonWithType returns type AnyObject, so you need to cast it as a UIButton
                                      – Chris C
                                      Sep 19 '14 at 13:07






                                    • 1




                                      @ElgsQianChen You can use this code according to your requirement. for example you want to add a UIButton when view appear you add the code in viewWillAppear.
                                      – Akhtar
                                      Sep 25 '14 at 12:06








                                    • 1




                                      As of Swift 1.2 downcasts can no longer be done with "as", they must be “forced failable” with "as!".
                                      – TenaciousJay
                                      May 1 '15 at 16:38










                                    • For people who run into Objective C String literals deprecated warnings Correct answer is here: stackoverflow.com/a/36308587/968848
                                      – n.by.n
                                      Mar 30 '16 at 12:27













                                    up vote
                                    95
                                    down vote










                                    up vote
                                    95
                                    down vote









                                    You can add UIButton,UIlable and UITextfield programmatically in this way.



                                    UIButton code



                                    // var button   = UIButton.buttonWithType(UIButtonType.System) as UIButton
                                    let button = UIButton(type: .System) // let preferred over var here
                                    button.frame = CGRectMake(100, 100, 100, 50)
                                    button.backgroundColor = UIColor.greenColor()
                                    button.setTitle("Button", forState: UIControlState.Normal)
                                    button.addTarget(self, action: "Action:", forControlEvents: UIControlEvents.TouchUpInside)
                                    self.view.addSubview(button)


                                    UILabel Code



                                    var label: UILabel = UILabel()
                                    label.frame = CGRectMake(50, 50, 200, 21)
                                    label.backgroundColor = UIColor.blackColor()
                                    label.textColor = UIColor.whiteColor()
                                    label.textAlignment = NSTextAlignment.Center
                                    label.text = "test label"
                                    self.view.addSubview(label)


                                    UITextField code



                                    var txtField: UITextField = UITextField()
                                    txtField.frame = CGRectMake(50, 70, 200, 30)
                                    txtField.backgroundColor = UIColor.grayColor()
                                    self.view.addSubview(txtField)


                                    Hope this is helpful for you.






                                    share|improve this answer














                                    You can add UIButton,UIlable and UITextfield programmatically in this way.



                                    UIButton code



                                    // var button   = UIButton.buttonWithType(UIButtonType.System) as UIButton
                                    let button = UIButton(type: .System) // let preferred over var here
                                    button.frame = CGRectMake(100, 100, 100, 50)
                                    button.backgroundColor = UIColor.greenColor()
                                    button.setTitle("Button", forState: UIControlState.Normal)
                                    button.addTarget(self, action: "Action:", forControlEvents: UIControlEvents.TouchUpInside)
                                    self.view.addSubview(button)


                                    UILabel Code



                                    var label: UILabel = UILabel()
                                    label.frame = CGRectMake(50, 50, 200, 21)
                                    label.backgroundColor = UIColor.blackColor()
                                    label.textColor = UIColor.whiteColor()
                                    label.textAlignment = NSTextAlignment.Center
                                    label.text = "test label"
                                    self.view.addSubview(label)


                                    UITextField code



                                    var txtField: UITextField = UITextField()
                                    txtField.frame = CGRectMake(50, 70, 200, 30)
                                    txtField.backgroundColor = UIColor.grayColor()
                                    self.view.addSubview(txtField)


                                    Hope this is helpful for you.







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Sep 29 '17 at 14:55









                                    Chandresh Kachariya

                                    61111024




                                    61111024










                                    answered Jun 6 '14 at 13:21









                                    Akhtar

                                    1,81531418




                                    1,81531418












                                    • so, why do you need the "as" operator in the first line of code you shared before UIButton...?
                                      – zumzum
                                      Jun 13 '14 at 22:32










                                    • buttonWithType returns type AnyObject, so you need to cast it as a UIButton
                                      – Chris C
                                      Sep 19 '14 at 13:07






                                    • 1




                                      @ElgsQianChen You can use this code according to your requirement. for example you want to add a UIButton when view appear you add the code in viewWillAppear.
                                      – Akhtar
                                      Sep 25 '14 at 12:06








                                    • 1




                                      As of Swift 1.2 downcasts can no longer be done with "as", they must be “forced failable” with "as!".
                                      – TenaciousJay
                                      May 1 '15 at 16:38










                                    • For people who run into Objective C String literals deprecated warnings Correct answer is here: stackoverflow.com/a/36308587/968848
                                      – n.by.n
                                      Mar 30 '16 at 12:27


















                                    • so, why do you need the "as" operator in the first line of code you shared before UIButton...?
                                      – zumzum
                                      Jun 13 '14 at 22:32










                                    • buttonWithType returns type AnyObject, so you need to cast it as a UIButton
                                      – Chris C
                                      Sep 19 '14 at 13:07






                                    • 1




                                      @ElgsQianChen You can use this code according to your requirement. for example you want to add a UIButton when view appear you add the code in viewWillAppear.
                                      – Akhtar
                                      Sep 25 '14 at 12:06








                                    • 1




                                      As of Swift 1.2 downcasts can no longer be done with "as", they must be “forced failable” with "as!".
                                      – TenaciousJay
                                      May 1 '15 at 16:38










                                    • For people who run into Objective C String literals deprecated warnings Correct answer is here: stackoverflow.com/a/36308587/968848
                                      – n.by.n
                                      Mar 30 '16 at 12:27
















                                    so, why do you need the "as" operator in the first line of code you shared before UIButton...?
                                    – zumzum
                                    Jun 13 '14 at 22:32




                                    so, why do you need the "as" operator in the first line of code you shared before UIButton...?
                                    – zumzum
                                    Jun 13 '14 at 22:32












                                    buttonWithType returns type AnyObject, so you need to cast it as a UIButton
                                    – Chris C
                                    Sep 19 '14 at 13:07




                                    buttonWithType returns type AnyObject, so you need to cast it as a UIButton
                                    – Chris C
                                    Sep 19 '14 at 13:07




                                    1




                                    1




                                    @ElgsQianChen You can use this code according to your requirement. for example you want to add a UIButton when view appear you add the code in viewWillAppear.
                                    – Akhtar
                                    Sep 25 '14 at 12:06






                                    @ElgsQianChen You can use this code according to your requirement. for example you want to add a UIButton when view appear you add the code in viewWillAppear.
                                    – Akhtar
                                    Sep 25 '14 at 12:06






                                    1




                                    1




                                    As of Swift 1.2 downcasts can no longer be done with "as", they must be “forced failable” with "as!".
                                    – TenaciousJay
                                    May 1 '15 at 16:38




                                    As of Swift 1.2 downcasts can no longer be done with "as", they must be “forced failable” with "as!".
                                    – TenaciousJay
                                    May 1 '15 at 16:38












                                    For people who run into Objective C String literals deprecated warnings Correct answer is here: stackoverflow.com/a/36308587/968848
                                    – n.by.n
                                    Mar 30 '16 at 12:27




                                    For people who run into Objective C String literals deprecated warnings Correct answer is here: stackoverflow.com/a/36308587/968848
                                    – n.by.n
                                    Mar 30 '16 at 12:27










                                    up vote
                                    54
                                    down vote













                                    For Swift 3



                                    let button = UIButton()
                                    button.frame = CGRect(x: self.view.frame.size.width - 60, y: 60, width: 50, height: 50)
                                    button.backgroundColor = UIColor.red
                                    button.setTitle("Name your Button ", for: .normal)
                                    button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
                                    self.view.addSubview(button)

                                    func buttonAction(sender: UIButton!) {
                                    print("Button tapped")
                                    }


                                    For Swift 4



                                     let button = UIButton()
                                    button.frame = CGRect(x: self.view.frame.size.width - 60, y: 60, width: 50, height: 50)
                                    button.backgroundColor = UIColor.red
                                    button.setTitle("Name your Button ", for: .normal)
                                    button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
                                    self.view.addSubview(button)

                                    @objc func buttonAction(sender: UIButton!) {
                                    print("Button tapped")
                                    }





                                    share|improve this answer























                                    • button.frame = (frame: CGRect(x: self.view.frame.size.width - 60, y: 20, width: 50, height: 50)) should be button.frame = CGRect(x: self.view.frame.size.width - 60, y: 20, width: 50, height: 50)
                                      – J.C
                                      Mar 30 '17 at 15:40






                                    • 2




                                      In Swift 4 before "func" need to add "@objc".
                                      – Ruslan Leshchenko
                                      Mar 19 at 8:10















                                    up vote
                                    54
                                    down vote













                                    For Swift 3



                                    let button = UIButton()
                                    button.frame = CGRect(x: self.view.frame.size.width - 60, y: 60, width: 50, height: 50)
                                    button.backgroundColor = UIColor.red
                                    button.setTitle("Name your Button ", for: .normal)
                                    button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
                                    self.view.addSubview(button)

                                    func buttonAction(sender: UIButton!) {
                                    print("Button tapped")
                                    }


                                    For Swift 4



                                     let button = UIButton()
                                    button.frame = CGRect(x: self.view.frame.size.width - 60, y: 60, width: 50, height: 50)
                                    button.backgroundColor = UIColor.red
                                    button.setTitle("Name your Button ", for: .normal)
                                    button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
                                    self.view.addSubview(button)

                                    @objc func buttonAction(sender: UIButton!) {
                                    print("Button tapped")
                                    }





                                    share|improve this answer























                                    • button.frame = (frame: CGRect(x: self.view.frame.size.width - 60, y: 20, width: 50, height: 50)) should be button.frame = CGRect(x: self.view.frame.size.width - 60, y: 20, width: 50, height: 50)
                                      – J.C
                                      Mar 30 '17 at 15:40






                                    • 2




                                      In Swift 4 before "func" need to add "@objc".
                                      – Ruslan Leshchenko
                                      Mar 19 at 8:10













                                    up vote
                                    54
                                    down vote










                                    up vote
                                    54
                                    down vote









                                    For Swift 3



                                    let button = UIButton()
                                    button.frame = CGRect(x: self.view.frame.size.width - 60, y: 60, width: 50, height: 50)
                                    button.backgroundColor = UIColor.red
                                    button.setTitle("Name your Button ", for: .normal)
                                    button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
                                    self.view.addSubview(button)

                                    func buttonAction(sender: UIButton!) {
                                    print("Button tapped")
                                    }


                                    For Swift 4



                                     let button = UIButton()
                                    button.frame = CGRect(x: self.view.frame.size.width - 60, y: 60, width: 50, height: 50)
                                    button.backgroundColor = UIColor.red
                                    button.setTitle("Name your Button ", for: .normal)
                                    button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
                                    self.view.addSubview(button)

                                    @objc func buttonAction(sender: UIButton!) {
                                    print("Button tapped")
                                    }





                                    share|improve this answer














                                    For Swift 3



                                    let button = UIButton()
                                    button.frame = CGRect(x: self.view.frame.size.width - 60, y: 60, width: 50, height: 50)
                                    button.backgroundColor = UIColor.red
                                    button.setTitle("Name your Button ", for: .normal)
                                    button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
                                    self.view.addSubview(button)

                                    func buttonAction(sender: UIButton!) {
                                    print("Button tapped")
                                    }


                                    For Swift 4



                                     let button = UIButton()
                                    button.frame = CGRect(x: self.view.frame.size.width - 60, y: 60, width: 50, height: 50)
                                    button.backgroundColor = UIColor.red
                                    button.setTitle("Name your Button ", for: .normal)
                                    button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
                                    self.view.addSubview(button)

                                    @objc func buttonAction(sender: UIButton!) {
                                    print("Button tapped")
                                    }






                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Mar 22 at 16:04

























                                    answered Nov 2 '16 at 12:38









                                    Museer Ahamad Ansari

                                    2,9672534




                                    2,9672534












                                    • button.frame = (frame: CGRect(x: self.view.frame.size.width - 60, y: 20, width: 50, height: 50)) should be button.frame = CGRect(x: self.view.frame.size.width - 60, y: 20, width: 50, height: 50)
                                      – J.C
                                      Mar 30 '17 at 15:40






                                    • 2




                                      In Swift 4 before "func" need to add "@objc".
                                      – Ruslan Leshchenko
                                      Mar 19 at 8:10


















                                    • button.frame = (frame: CGRect(x: self.view.frame.size.width - 60, y: 20, width: 50, height: 50)) should be button.frame = CGRect(x: self.view.frame.size.width - 60, y: 20, width: 50, height: 50)
                                      – J.C
                                      Mar 30 '17 at 15:40






                                    • 2




                                      In Swift 4 before "func" need to add "@objc".
                                      – Ruslan Leshchenko
                                      Mar 19 at 8:10
















                                    button.frame = (frame: CGRect(x: self.view.frame.size.width - 60, y: 20, width: 50, height: 50)) should be button.frame = CGRect(x: self.view.frame.size.width - 60, y: 20, width: 50, height: 50)
                                    – J.C
                                    Mar 30 '17 at 15:40




                                    button.frame = (frame: CGRect(x: self.view.frame.size.width - 60, y: 20, width: 50, height: 50)) should be button.frame = CGRect(x: self.view.frame.size.width - 60, y: 20, width: 50, height: 50)
                                    – J.C
                                    Mar 30 '17 at 15:40




                                    2




                                    2




                                    In Swift 4 before "func" need to add "@objc".
                                    – Ruslan Leshchenko
                                    Mar 19 at 8:10




                                    In Swift 4 before "func" need to add "@objc".
                                    – Ruslan Leshchenko
                                    Mar 19 at 8:10










                                    up vote
                                    29
                                    down vote













                                    Swift 3



                                    let btn = UIButton(type: .custom) as UIButton
                                    btn.backgroundColor = .blue
                                    btn.setTitle("Button", for: .normal)
                                    btn.frame = CGRect(x: 100, y: 100, width: 200, height: 100)
                                    btn.addTarget(self, action: #selector(clickMe), for: .touchUpInside)
                                    self.view.addSubview(btn)

                                    func clickMe(sender:UIButton!) {
                                    print("Button Clicked")
                                    }


                                    Output



                                    enter image description here






                                    share|improve this answer























                                    • Thanks, m8! Starting up with Swift today so everything is kind of strange (:
                                      – Felipe
                                      Oct 27 '15 at 18:13















                                    up vote
                                    29
                                    down vote













                                    Swift 3



                                    let btn = UIButton(type: .custom) as UIButton
                                    btn.backgroundColor = .blue
                                    btn.setTitle("Button", for: .normal)
                                    btn.frame = CGRect(x: 100, y: 100, width: 200, height: 100)
                                    btn.addTarget(self, action: #selector(clickMe), for: .touchUpInside)
                                    self.view.addSubview(btn)

                                    func clickMe(sender:UIButton!) {
                                    print("Button Clicked")
                                    }


                                    Output



                                    enter image description here






                                    share|improve this answer























                                    • Thanks, m8! Starting up with Swift today so everything is kind of strange (:
                                      – Felipe
                                      Oct 27 '15 at 18:13













                                    up vote
                                    29
                                    down vote










                                    up vote
                                    29
                                    down vote









                                    Swift 3



                                    let btn = UIButton(type: .custom) as UIButton
                                    btn.backgroundColor = .blue
                                    btn.setTitle("Button", for: .normal)
                                    btn.frame = CGRect(x: 100, y: 100, width: 200, height: 100)
                                    btn.addTarget(self, action: #selector(clickMe), for: .touchUpInside)
                                    self.view.addSubview(btn)

                                    func clickMe(sender:UIButton!) {
                                    print("Button Clicked")
                                    }


                                    Output



                                    enter image description here






                                    share|improve this answer














                                    Swift 3



                                    let btn = UIButton(type: .custom) as UIButton
                                    btn.backgroundColor = .blue
                                    btn.setTitle("Button", for: .normal)
                                    btn.frame = CGRect(x: 100, y: 100, width: 200, height: 100)
                                    btn.addTarget(self, action: #selector(clickMe), for: .touchUpInside)
                                    self.view.addSubview(btn)

                                    func clickMe(sender:UIButton!) {
                                    print("Button Clicked")
                                    }


                                    Output



                                    enter image description here







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited May 22 '17 at 13:41









                                    John R Perry

                                    1,6551537




                                    1,6551537










                                    answered Oct 8 '15 at 12:33









                                    user3182143

                                    7,73332030




                                    7,73332030












                                    • Thanks, m8! Starting up with Swift today so everything is kind of strange (:
                                      – Felipe
                                      Oct 27 '15 at 18:13


















                                    • Thanks, m8! Starting up with Swift today so everything is kind of strange (:
                                      – Felipe
                                      Oct 27 '15 at 18:13
















                                    Thanks, m8! Starting up with Swift today so everything is kind of strange (:
                                    – Felipe
                                    Oct 27 '15 at 18:13




                                    Thanks, m8! Starting up with Swift today so everything is kind of strange (:
                                    – Felipe
                                    Oct 27 '15 at 18:13










                                    up vote
                                    16
                                    down vote













                                    How to do this using Swift 3.0.



                                    func createButton() {
                                    let button = UIButton(type: .system)
                                    button.frame = CGRect(x: 100.0, y: 100.0, width: 100.0, height: 100.0)
                                    button.setTitle(NSLocalizedString("Button", comment: "Button"), for: .normal)
                                    button.backgroundColor = .green
                                    button.addTarget(self, action: #selector(buttonAction(sender:)), for: .touchUpInside)
                                    view.addSubview(button)
                                    }

                                    @objc func buttonAction(sender: UIButton) {
                                    print("Button pushed")
                                    }





                                    share|improve this answer

























                                      up vote
                                      16
                                      down vote













                                      How to do this using Swift 3.0.



                                      func createButton() {
                                      let button = UIButton(type: .system)
                                      button.frame = CGRect(x: 100.0, y: 100.0, width: 100.0, height: 100.0)
                                      button.setTitle(NSLocalizedString("Button", comment: "Button"), for: .normal)
                                      button.backgroundColor = .green
                                      button.addTarget(self, action: #selector(buttonAction(sender:)), for: .touchUpInside)
                                      view.addSubview(button)
                                      }

                                      @objc func buttonAction(sender: UIButton) {
                                      print("Button pushed")
                                      }





                                      share|improve this answer























                                        up vote
                                        16
                                        down vote










                                        up vote
                                        16
                                        down vote









                                        How to do this using Swift 3.0.



                                        func createButton() {
                                        let button = UIButton(type: .system)
                                        button.frame = CGRect(x: 100.0, y: 100.0, width: 100.0, height: 100.0)
                                        button.setTitle(NSLocalizedString("Button", comment: "Button"), for: .normal)
                                        button.backgroundColor = .green
                                        button.addTarget(self, action: #selector(buttonAction(sender:)), for: .touchUpInside)
                                        view.addSubview(button)
                                        }

                                        @objc func buttonAction(sender: UIButton) {
                                        print("Button pushed")
                                        }





                                        share|improve this answer












                                        How to do this using Swift 3.0.



                                        func createButton() {
                                        let button = UIButton(type: .system)
                                        button.frame = CGRect(x: 100.0, y: 100.0, width: 100.0, height: 100.0)
                                        button.setTitle(NSLocalizedString("Button", comment: "Button"), for: .normal)
                                        button.backgroundColor = .green
                                        button.addTarget(self, action: #selector(buttonAction(sender:)), for: .touchUpInside)
                                        view.addSubview(button)
                                        }

                                        @objc func buttonAction(sender: UIButton) {
                                        print("Button pushed")
                                        }






                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Oct 19 '16 at 19:04









                                        CodeBender

                                        10.2k55052




                                        10.2k55052






















                                            up vote
                                            13
                                            down vote













                                             var sampleButton:UIButton?

                                            override func viewDidLoad() {
                                            super.viewDidLoad()

                                            }
                                            override func viewDidAppear(animated: Bool) {

                                            sampleButton = UIButton(type: .RoundedRect)
                                            //sampleButton.frame = CGRect(x:50, y:500, width:70, height:50)

                                            sampleButton!.setTitle("Sample n UI Button", forState: .Normal)
                                            sampleButton!.titleLabel?.lineBreakMode = .ByWordWrapping
                                            sampleButton!.titleLabel?.textAlignment = .Center
                                            sampleButton!.setTitleColor(UIColor.whiteColor(), forState: .Normal)
                                            sampleButton!.layer.cornerRadius = 6
                                            sampleButton!.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.6)
                                            sampleButton?.tintColor = UIColor.brownColor()


                                            //Add padding around text
                                            sampleButton!.titleEdgeInsets = UIEdgeInsetsMake(-10,-10,-10,-10)
                                            sampleButton!.contentEdgeInsets = UIEdgeInsetsMake(5,5,5,5)

                                            //Action set up
                                            sampleButton!.addTarget(self, action: "sampleButtonClicked", forControlEvents: .TouchUpInside)
                                            self.view.addSubview(sampleButton!)


                                            //Button Constraints:
                                            sampleButton!.translatesAutoresizingMaskIntoConstraints = false

                                            //To anchor above the tab bar on the bottom of the screen:
                                            let bottomButtonConstraint = sampleButton!.bottomAnchor.constraintEqualToAnchor(bottomLayoutGuide.topAnchor, constant: -20)

                                            //edge of the screen in InterfaceBuilder:
                                            let margins = view.layoutMarginsGuide
                                            let leadingButtonConstraint = sampleButton!.leadingAnchor.constraintEqualToAnchor(margins.leadingAnchor)

                                            bottomButtonConstraint.active = true
                                            leadingButtonConstraint.active = true


                                            }
                                            func sampleButtonClicked(){

                                            print("sample Button Clicked")

                                            }





                                            share|improve this answer

























                                              up vote
                                              13
                                              down vote













                                               var sampleButton:UIButton?

                                              override func viewDidLoad() {
                                              super.viewDidLoad()

                                              }
                                              override func viewDidAppear(animated: Bool) {

                                              sampleButton = UIButton(type: .RoundedRect)
                                              //sampleButton.frame = CGRect(x:50, y:500, width:70, height:50)

                                              sampleButton!.setTitle("Sample n UI Button", forState: .Normal)
                                              sampleButton!.titleLabel?.lineBreakMode = .ByWordWrapping
                                              sampleButton!.titleLabel?.textAlignment = .Center
                                              sampleButton!.setTitleColor(UIColor.whiteColor(), forState: .Normal)
                                              sampleButton!.layer.cornerRadius = 6
                                              sampleButton!.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.6)
                                              sampleButton?.tintColor = UIColor.brownColor()


                                              //Add padding around text
                                              sampleButton!.titleEdgeInsets = UIEdgeInsetsMake(-10,-10,-10,-10)
                                              sampleButton!.contentEdgeInsets = UIEdgeInsetsMake(5,5,5,5)

                                              //Action set up
                                              sampleButton!.addTarget(self, action: "sampleButtonClicked", forControlEvents: .TouchUpInside)
                                              self.view.addSubview(sampleButton!)


                                              //Button Constraints:
                                              sampleButton!.translatesAutoresizingMaskIntoConstraints = false

                                              //To anchor above the tab bar on the bottom of the screen:
                                              let bottomButtonConstraint = sampleButton!.bottomAnchor.constraintEqualToAnchor(bottomLayoutGuide.topAnchor, constant: -20)

                                              //edge of the screen in InterfaceBuilder:
                                              let margins = view.layoutMarginsGuide
                                              let leadingButtonConstraint = sampleButton!.leadingAnchor.constraintEqualToAnchor(margins.leadingAnchor)

                                              bottomButtonConstraint.active = true
                                              leadingButtonConstraint.active = true


                                              }
                                              func sampleButtonClicked(){

                                              print("sample Button Clicked")

                                              }





                                              share|improve this answer























                                                up vote
                                                13
                                                down vote










                                                up vote
                                                13
                                                down vote









                                                 var sampleButton:UIButton?

                                                override func viewDidLoad() {
                                                super.viewDidLoad()

                                                }
                                                override func viewDidAppear(animated: Bool) {

                                                sampleButton = UIButton(type: .RoundedRect)
                                                //sampleButton.frame = CGRect(x:50, y:500, width:70, height:50)

                                                sampleButton!.setTitle("Sample n UI Button", forState: .Normal)
                                                sampleButton!.titleLabel?.lineBreakMode = .ByWordWrapping
                                                sampleButton!.titleLabel?.textAlignment = .Center
                                                sampleButton!.setTitleColor(UIColor.whiteColor(), forState: .Normal)
                                                sampleButton!.layer.cornerRadius = 6
                                                sampleButton!.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.6)
                                                sampleButton?.tintColor = UIColor.brownColor()


                                                //Add padding around text
                                                sampleButton!.titleEdgeInsets = UIEdgeInsetsMake(-10,-10,-10,-10)
                                                sampleButton!.contentEdgeInsets = UIEdgeInsetsMake(5,5,5,5)

                                                //Action set up
                                                sampleButton!.addTarget(self, action: "sampleButtonClicked", forControlEvents: .TouchUpInside)
                                                self.view.addSubview(sampleButton!)


                                                //Button Constraints:
                                                sampleButton!.translatesAutoresizingMaskIntoConstraints = false

                                                //To anchor above the tab bar on the bottom of the screen:
                                                let bottomButtonConstraint = sampleButton!.bottomAnchor.constraintEqualToAnchor(bottomLayoutGuide.topAnchor, constant: -20)

                                                //edge of the screen in InterfaceBuilder:
                                                let margins = view.layoutMarginsGuide
                                                let leadingButtonConstraint = sampleButton!.leadingAnchor.constraintEqualToAnchor(margins.leadingAnchor)

                                                bottomButtonConstraint.active = true
                                                leadingButtonConstraint.active = true


                                                }
                                                func sampleButtonClicked(){

                                                print("sample Button Clicked")

                                                }





                                                share|improve this answer












                                                 var sampleButton:UIButton?

                                                override func viewDidLoad() {
                                                super.viewDidLoad()

                                                }
                                                override func viewDidAppear(animated: Bool) {

                                                sampleButton = UIButton(type: .RoundedRect)
                                                //sampleButton.frame = CGRect(x:50, y:500, width:70, height:50)

                                                sampleButton!.setTitle("Sample n UI Button", forState: .Normal)
                                                sampleButton!.titleLabel?.lineBreakMode = .ByWordWrapping
                                                sampleButton!.titleLabel?.textAlignment = .Center
                                                sampleButton!.setTitleColor(UIColor.whiteColor(), forState: .Normal)
                                                sampleButton!.layer.cornerRadius = 6
                                                sampleButton!.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.6)
                                                sampleButton?.tintColor = UIColor.brownColor()


                                                //Add padding around text
                                                sampleButton!.titleEdgeInsets = UIEdgeInsetsMake(-10,-10,-10,-10)
                                                sampleButton!.contentEdgeInsets = UIEdgeInsetsMake(5,5,5,5)

                                                //Action set up
                                                sampleButton!.addTarget(self, action: "sampleButtonClicked", forControlEvents: .TouchUpInside)
                                                self.view.addSubview(sampleButton!)


                                                //Button Constraints:
                                                sampleButton!.translatesAutoresizingMaskIntoConstraints = false

                                                //To anchor above the tab bar on the bottom of the screen:
                                                let bottomButtonConstraint = sampleButton!.bottomAnchor.constraintEqualToAnchor(bottomLayoutGuide.topAnchor, constant: -20)

                                                //edge of the screen in InterfaceBuilder:
                                                let margins = view.layoutMarginsGuide
                                                let leadingButtonConstraint = sampleButton!.leadingAnchor.constraintEqualToAnchor(margins.leadingAnchor)

                                                bottomButtonConstraint.active = true
                                                leadingButtonConstraint.active = true


                                                }
                                                func sampleButtonClicked(){

                                                print("sample Button Clicked")

                                                }






                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Mar 22 '16 at 6:41









                                                A.G

                                                10.2k7148




                                                10.2k7148






















                                                    up vote
                                                    13
                                                    down vote













                                                    The API hasn't changed - only the syntax has. You can make a UIButton and add it like this:



                                                    var button = UIButton(frame: CGRectMake(0, 0, 50, 50))
                                                    self.view.addSubview(button) // assuming you're in a view controller





                                                    share|improve this answer



























                                                      up vote
                                                      13
                                                      down vote













                                                      The API hasn't changed - only the syntax has. You can make a UIButton and add it like this:



                                                      var button = UIButton(frame: CGRectMake(0, 0, 50, 50))
                                                      self.view.addSubview(button) // assuming you're in a view controller





                                                      share|improve this answer

























                                                        up vote
                                                        13
                                                        down vote










                                                        up vote
                                                        13
                                                        down vote









                                                        The API hasn't changed - only the syntax has. You can make a UIButton and add it like this:



                                                        var button = UIButton(frame: CGRectMake(0, 0, 50, 50))
                                                        self.view.addSubview(button) // assuming you're in a view controller





                                                        share|improve this answer














                                                        The API hasn't changed - only the syntax has. You can make a UIButton and add it like this:



                                                        var button = UIButton(frame: CGRectMake(0, 0, 50, 50))
                                                        self.view.addSubview(button) // assuming you're in a view controller






                                                        share|improve this answer














                                                        share|improve this answer



                                                        share|improve this answer








                                                        edited Aug 19 '16 at 1:00

























                                                        answered Jun 4 '14 at 6:25









                                                        Cezary Wojcik

                                                        18.5k63135




                                                        18.5k63135






















                                                            up vote
                                                            6
                                                            down vote













                                                            Add this code in viewDidLoad

                                                            //add Button



                                                                        var button=UIButton(frame: CGRectMake(150, 240, 75, 30))
                                                            button.setTitle("Next", forState: UIControlState.Normal)
                                                            button.addTarget(self, action: "buttonTapAction:", forControlEvents: UIControlEvents.TouchUpInside)
                                                            button.backgroundColor = UIColor.greenColor()
                                                            self.view.addSubview(button)


                                                            Write this function outside it,this will call when you tap on the button



                                                            func buttonTapAction(sender:UIButton!)
                                                            {
                                                            println("Button is working")
                                                            }





                                                            share|improve this answer

























                                                              up vote
                                                              6
                                                              down vote













                                                              Add this code in viewDidLoad

                                                              //add Button



                                                                          var button=UIButton(frame: CGRectMake(150, 240, 75, 30))
                                                              button.setTitle("Next", forState: UIControlState.Normal)
                                                              button.addTarget(self, action: "buttonTapAction:", forControlEvents: UIControlEvents.TouchUpInside)
                                                              button.backgroundColor = UIColor.greenColor()
                                                              self.view.addSubview(button)


                                                              Write this function outside it,this will call when you tap on the button



                                                              func buttonTapAction(sender:UIButton!)
                                                              {
                                                              println("Button is working")
                                                              }





                                                              share|improve this answer























                                                                up vote
                                                                6
                                                                down vote










                                                                up vote
                                                                6
                                                                down vote









                                                                Add this code in viewDidLoad

                                                                //add Button



                                                                            var button=UIButton(frame: CGRectMake(150, 240, 75, 30))
                                                                button.setTitle("Next", forState: UIControlState.Normal)
                                                                button.addTarget(self, action: "buttonTapAction:", forControlEvents: UIControlEvents.TouchUpInside)
                                                                button.backgroundColor = UIColor.greenColor()
                                                                self.view.addSubview(button)


                                                                Write this function outside it,this will call when you tap on the button



                                                                func buttonTapAction(sender:UIButton!)
                                                                {
                                                                println("Button is working")
                                                                }





                                                                share|improve this answer












                                                                Add this code in viewDidLoad

                                                                //add Button



                                                                            var button=UIButton(frame: CGRectMake(150, 240, 75, 30))
                                                                button.setTitle("Next", forState: UIControlState.Normal)
                                                                button.addTarget(self, action: "buttonTapAction:", forControlEvents: UIControlEvents.TouchUpInside)
                                                                button.backgroundColor = UIColor.greenColor()
                                                                self.view.addSubview(button)


                                                                Write this function outside it,this will call when you tap on the button



                                                                func buttonTapAction(sender:UIButton!)
                                                                {
                                                                println("Button is working")
                                                                }






                                                                share|improve this answer












                                                                share|improve this answer



                                                                share|improve this answer










                                                                answered May 13 '15 at 10:05









                                                                Nimmy Alphonsa Jose

                                                                6616




                                                                6616






















                                                                    up vote
                                                                    6
                                                                    down vote













                                                                    In Swift 2 and iOS 9.2.1



                                                                    var button: UIButton = UIButton(type: UIButtonType.Custom) as UIButton
                                                                    self.button.frame = CGRectMake(130, 70, 60, 20)
                                                                    self.button.setTitle("custom button", forState: UIControlState.Normal)
                                                                    self.button.addTarget(self, action:"buttonActionFuncName", forControlEvents: UIControlEvents.TouchUpInside)
                                                                    self.button.setTitleColor(UIColor.blackColor(), forState: .Normal)
                                                                    self.button.layer.borderColor = UIColor.blackColor().CGColor
                                                                    self.button.titleLabel?.font = UIFont(name: "Helvetica-Bold", size: 13)
                                                                    self.view.addSubview(self.button)





                                                                    share|improve this answer



























                                                                      up vote
                                                                      6
                                                                      down vote













                                                                      In Swift 2 and iOS 9.2.1



                                                                      var button: UIButton = UIButton(type: UIButtonType.Custom) as UIButton
                                                                      self.button.frame = CGRectMake(130, 70, 60, 20)
                                                                      self.button.setTitle("custom button", forState: UIControlState.Normal)
                                                                      self.button.addTarget(self, action:"buttonActionFuncName", forControlEvents: UIControlEvents.TouchUpInside)
                                                                      self.button.setTitleColor(UIColor.blackColor(), forState: .Normal)
                                                                      self.button.layer.borderColor = UIColor.blackColor().CGColor
                                                                      self.button.titleLabel?.font = UIFont(name: "Helvetica-Bold", size: 13)
                                                                      self.view.addSubview(self.button)





                                                                      share|improve this answer

























                                                                        up vote
                                                                        6
                                                                        down vote










                                                                        up vote
                                                                        6
                                                                        down vote









                                                                        In Swift 2 and iOS 9.2.1



                                                                        var button: UIButton = UIButton(type: UIButtonType.Custom) as UIButton
                                                                        self.button.frame = CGRectMake(130, 70, 60, 20)
                                                                        self.button.setTitle("custom button", forState: UIControlState.Normal)
                                                                        self.button.addTarget(self, action:"buttonActionFuncName", forControlEvents: UIControlEvents.TouchUpInside)
                                                                        self.button.setTitleColor(UIColor.blackColor(), forState: .Normal)
                                                                        self.button.layer.borderColor = UIColor.blackColor().CGColor
                                                                        self.button.titleLabel?.font = UIFont(name: "Helvetica-Bold", size: 13)
                                                                        self.view.addSubview(self.button)





                                                                        share|improve this answer














                                                                        In Swift 2 and iOS 9.2.1



                                                                        var button: UIButton = UIButton(type: UIButtonType.Custom) as UIButton
                                                                        self.button.frame = CGRectMake(130, 70, 60, 20)
                                                                        self.button.setTitle("custom button", forState: UIControlState.Normal)
                                                                        self.button.addTarget(self, action:"buttonActionFuncName", forControlEvents: UIControlEvents.TouchUpInside)
                                                                        self.button.setTitleColor(UIColor.blackColor(), forState: .Normal)
                                                                        self.button.layer.borderColor = UIColor.blackColor().CGColor
                                                                        self.button.titleLabel?.font = UIFont(name: "Helvetica-Bold", size: 13)
                                                                        self.view.addSubview(self.button)






                                                                        share|improve this answer














                                                                        share|improve this answer



                                                                        share|improve this answer








                                                                        edited Feb 24 '16 at 6:30

























                                                                        answered Jan 29 '16 at 6:28









                                                                        Muhammad Qasim

                                                                        13426




                                                                        13426






















                                                                            up vote
                                                                            6
                                                                            down vote













                                                                            You can create like this and you can add action also like this....



                                                                            import UIKit

                                                                            let myButton = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50))

                                                                            init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!)
                                                                            { super.init(nibName: nibName, bundle: nibBundle)
                                                                            myButton.targetForAction("tappedButton:", withSender: self)
                                                                            }

                                                                            func tappedButton(sender: UIButton!)
                                                                            {
                                                                            println("tapped button")
                                                                            }





                                                                            share|improve this answer























                                                                            • sorry, but the compiler sent error in line - self.view.addSubview(view: myButton). Error is next: "Extraneous argument label 'view:' in call"
                                                                              – val_lek
                                                                              Jun 4 '14 at 7:26










                                                                            • Please remove this line self.view.addSubview(view: myButton) For more info see my edited answer.
                                                                              – Dharmbir Singh
                                                                              Jun 4 '14 at 7:26












                                                                            • Thank you, but how I can add this button on self.view?
                                                                              – val_lek
                                                                              Jun 4 '14 at 7:31















                                                                            up vote
                                                                            6
                                                                            down vote













                                                                            You can create like this and you can add action also like this....



                                                                            import UIKit

                                                                            let myButton = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50))

                                                                            init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!)
                                                                            { super.init(nibName: nibName, bundle: nibBundle)
                                                                            myButton.targetForAction("tappedButton:", withSender: self)
                                                                            }

                                                                            func tappedButton(sender: UIButton!)
                                                                            {
                                                                            println("tapped button")
                                                                            }





                                                                            share|improve this answer























                                                                            • sorry, but the compiler sent error in line - self.view.addSubview(view: myButton). Error is next: "Extraneous argument label 'view:' in call"
                                                                              – val_lek
                                                                              Jun 4 '14 at 7:26










                                                                            • Please remove this line self.view.addSubview(view: myButton) For more info see my edited answer.
                                                                              – Dharmbir Singh
                                                                              Jun 4 '14 at 7:26












                                                                            • Thank you, but how I can add this button on self.view?
                                                                              – val_lek
                                                                              Jun 4 '14 at 7:31













                                                                            up vote
                                                                            6
                                                                            down vote










                                                                            up vote
                                                                            6
                                                                            down vote









                                                                            You can create like this and you can add action also like this....



                                                                            import UIKit

                                                                            let myButton = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50))

                                                                            init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!)
                                                                            { super.init(nibName: nibName, bundle: nibBundle)
                                                                            myButton.targetForAction("tappedButton:", withSender: self)
                                                                            }

                                                                            func tappedButton(sender: UIButton!)
                                                                            {
                                                                            println("tapped button")
                                                                            }





                                                                            share|improve this answer














                                                                            You can create like this and you can add action also like this....



                                                                            import UIKit

                                                                            let myButton = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50))

                                                                            init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!)
                                                                            { super.init(nibName: nibName, bundle: nibBundle)
                                                                            myButton.targetForAction("tappedButton:", withSender: self)
                                                                            }

                                                                            func tappedButton(sender: UIButton!)
                                                                            {
                                                                            println("tapped button")
                                                                            }






                                                                            share|improve this answer














                                                                            share|improve this answer



                                                                            share|improve this answer








                                                                            edited Sep 29 '17 at 13:05









                                                                            Chandresh Kachariya

                                                                            61111024




                                                                            61111024










                                                                            answered Jun 4 '14 at 7:08









                                                                            Dharmbir Singh

                                                                            14.4k33656




                                                                            14.4k33656












                                                                            • sorry, but the compiler sent error in line - self.view.addSubview(view: myButton). Error is next: "Extraneous argument label 'view:' in call"
                                                                              – val_lek
                                                                              Jun 4 '14 at 7:26










                                                                            • Please remove this line self.view.addSubview(view: myButton) For more info see my edited answer.
                                                                              – Dharmbir Singh
                                                                              Jun 4 '14 at 7:26












                                                                            • Thank you, but how I can add this button on self.view?
                                                                              – val_lek
                                                                              Jun 4 '14 at 7:31


















                                                                            • sorry, but the compiler sent error in line - self.view.addSubview(view: myButton). Error is next: "Extraneous argument label 'view:' in call"
                                                                              – val_lek
                                                                              Jun 4 '14 at 7:26










                                                                            • Please remove this line self.view.addSubview(view: myButton) For more info see my edited answer.
                                                                              – Dharmbir Singh
                                                                              Jun 4 '14 at 7:26












                                                                            • Thank you, but how I can add this button on self.view?
                                                                              – val_lek
                                                                              Jun 4 '14 at 7:31
















                                                                            sorry, but the compiler sent error in line - self.view.addSubview(view: myButton). Error is next: "Extraneous argument label 'view:' in call"
                                                                            – val_lek
                                                                            Jun 4 '14 at 7:26




                                                                            sorry, but the compiler sent error in line - self.view.addSubview(view: myButton). Error is next: "Extraneous argument label 'view:' in call"
                                                                            – val_lek
                                                                            Jun 4 '14 at 7:26












                                                                            Please remove this line self.view.addSubview(view: myButton) For more info see my edited answer.
                                                                            – Dharmbir Singh
                                                                            Jun 4 '14 at 7:26






                                                                            Please remove this line self.view.addSubview(view: myButton) For more info see my edited answer.
                                                                            – Dharmbir Singh
                                                                            Jun 4 '14 at 7:26














                                                                            Thank you, but how I can add this button on self.view?
                                                                            – val_lek
                                                                            Jun 4 '14 at 7:31




                                                                            Thank you, but how I can add this button on self.view?
                                                                            – val_lek
                                                                            Jun 4 '14 at 7:31










                                                                            up vote
                                                                            4
                                                                            down vote













                                                                            It is possible. You do everything pretty much the same way except use the swift syntax. For example you could make a UIButton in code like this:



                                                                             var button: UIButton = UIButton(frame: CGRectMake(0, 0, 100, 100))





                                                                            share|improve this answer

























                                                                              up vote
                                                                              4
                                                                              down vote













                                                                              It is possible. You do everything pretty much the same way except use the swift syntax. For example you could make a UIButton in code like this:



                                                                               var button: UIButton = UIButton(frame: CGRectMake(0, 0, 100, 100))





                                                                              share|improve this answer























                                                                                up vote
                                                                                4
                                                                                down vote










                                                                                up vote
                                                                                4
                                                                                down vote









                                                                                It is possible. You do everything pretty much the same way except use the swift syntax. For example you could make a UIButton in code like this:



                                                                                 var button: UIButton = UIButton(frame: CGRectMake(0, 0, 100, 100))





                                                                                share|improve this answer












                                                                                It is possible. You do everything pretty much the same way except use the swift syntax. For example you could make a UIButton in code like this:



                                                                                 var button: UIButton = UIButton(frame: CGRectMake(0, 0, 100, 100))






                                                                                share|improve this answer












                                                                                share|improve this answer



                                                                                share|improve this answer










                                                                                answered Jun 4 '14 at 6:22









                                                                                Connor

                                                                                50.5k22113128




                                                                                50.5k22113128






















                                                                                    up vote
                                                                                    3
                                                                                    down vote













                                                                                    For create UIButton from storyboard:
                                                                                    1 - Drag UIButton object from Object Library to ViewController in storyboard file
                                                                                    2 - Show Assistant editor
                                                                                    3 - Drag with right click from UIButton create above into your class. The result is the following:



                                                                                    @IBAction func buttonActionFromStoryboard(sender: UIButton)
                                                                                    {
                                                                                    println("Button Action From Storyboard")
                                                                                    }


                                                                                    For create UIButton programmatically:
                                                                                    1- Write into "override func viewDidLoad()":



                                                                                            let uiButton    = UIButton.buttonWithType(UIButtonType.System) as UIButton
                                                                                    uiButton.frame = CGRectMake(16, 116, 288, 30)
                                                                                    uiButton.setTitle("Second", forState: UIControlState.Normal);
                                                                                    uiButton.addTarget(self, action: "buttonActionFromCode:", forControlEvents: UIControlEvents.TouchUpInside)
                                                                                    self.view.addSubview(uiButton)


                                                                                    2- add the IBAction func:



                                                                                    @IBAction func buttonActionFromCode(sender:UIButton)
                                                                                    {
                                                                                    println("Button Action From Code")
                                                                                    }





                                                                                    share|improve this answer





















                                                                                    • As of Swift 1.2 downcasts can no longer be done with "as", they must be “forced failable” with "as!".
                                                                                      – TenaciousJay
                                                                                      May 1 '15 at 16:38















                                                                                    up vote
                                                                                    3
                                                                                    down vote













                                                                                    For create UIButton from storyboard:
                                                                                    1 - Drag UIButton object from Object Library to ViewController in storyboard file
                                                                                    2 - Show Assistant editor
                                                                                    3 - Drag with right click from UIButton create above into your class. The result is the following:



                                                                                    @IBAction func buttonActionFromStoryboard(sender: UIButton)
                                                                                    {
                                                                                    println("Button Action From Storyboard")
                                                                                    }


                                                                                    For create UIButton programmatically:
                                                                                    1- Write into "override func viewDidLoad()":



                                                                                            let uiButton    = UIButton.buttonWithType(UIButtonType.System) as UIButton
                                                                                    uiButton.frame = CGRectMake(16, 116, 288, 30)
                                                                                    uiButton.setTitle("Second", forState: UIControlState.Normal);
                                                                                    uiButton.addTarget(self, action: "buttonActionFromCode:", forControlEvents: UIControlEvents.TouchUpInside)
                                                                                    self.view.addSubview(uiButton)


                                                                                    2- add the IBAction func:



                                                                                    @IBAction func buttonActionFromCode(sender:UIButton)
                                                                                    {
                                                                                    println("Button Action From Code")
                                                                                    }





                                                                                    share|improve this answer





















                                                                                    • As of Swift 1.2 downcasts can no longer be done with "as", they must be “forced failable” with "as!".
                                                                                      – TenaciousJay
                                                                                      May 1 '15 at 16:38













                                                                                    up vote
                                                                                    3
                                                                                    down vote










                                                                                    up vote
                                                                                    3
                                                                                    down vote









                                                                                    For create UIButton from storyboard:
                                                                                    1 - Drag UIButton object from Object Library to ViewController in storyboard file
                                                                                    2 - Show Assistant editor
                                                                                    3 - Drag with right click from UIButton create above into your class. The result is the following:



                                                                                    @IBAction func buttonActionFromStoryboard(sender: UIButton)
                                                                                    {
                                                                                    println("Button Action From Storyboard")
                                                                                    }


                                                                                    For create UIButton programmatically:
                                                                                    1- Write into "override func viewDidLoad()":



                                                                                            let uiButton    = UIButton.buttonWithType(UIButtonType.System) as UIButton
                                                                                    uiButton.frame = CGRectMake(16, 116, 288, 30)
                                                                                    uiButton.setTitle("Second", forState: UIControlState.Normal);
                                                                                    uiButton.addTarget(self, action: "buttonActionFromCode:", forControlEvents: UIControlEvents.TouchUpInside)
                                                                                    self.view.addSubview(uiButton)


                                                                                    2- add the IBAction func:



                                                                                    @IBAction func buttonActionFromCode(sender:UIButton)
                                                                                    {
                                                                                    println("Button Action From Code")
                                                                                    }





                                                                                    share|improve this answer












                                                                                    For create UIButton from storyboard:
                                                                                    1 - Drag UIButton object from Object Library to ViewController in storyboard file
                                                                                    2 - Show Assistant editor
                                                                                    3 - Drag with right click from UIButton create above into your class. The result is the following:



                                                                                    @IBAction func buttonActionFromStoryboard(sender: UIButton)
                                                                                    {
                                                                                    println("Button Action From Storyboard")
                                                                                    }


                                                                                    For create UIButton programmatically:
                                                                                    1- Write into "override func viewDidLoad()":



                                                                                            let uiButton    = UIButton.buttonWithType(UIButtonType.System) as UIButton
                                                                                    uiButton.frame = CGRectMake(16, 116, 288, 30)
                                                                                    uiButton.setTitle("Second", forState: UIControlState.Normal);
                                                                                    uiButton.addTarget(self, action: "buttonActionFromCode:", forControlEvents: UIControlEvents.TouchUpInside)
                                                                                    self.view.addSubview(uiButton)


                                                                                    2- add the IBAction func:



                                                                                    @IBAction func buttonActionFromCode(sender:UIButton)
                                                                                    {
                                                                                    println("Button Action From Code")
                                                                                    }






                                                                                    share|improve this answer












                                                                                    share|improve this answer



                                                                                    share|improve this answer










                                                                                    answered Sep 4 '14 at 10:08









                                                                                    Alessandro Pirovano

                                                                                    1,9661821




                                                                                    1,9661821












                                                                                    • As of Swift 1.2 downcasts can no longer be done with "as", they must be “forced failable” with "as!".
                                                                                      – TenaciousJay
                                                                                      May 1 '15 at 16:38


















                                                                                    • As of Swift 1.2 downcasts can no longer be done with "as", they must be “forced failable” with "as!".
                                                                                      – TenaciousJay
                                                                                      May 1 '15 at 16:38
















                                                                                    As of Swift 1.2 downcasts can no longer be done with "as", they must be “forced failable” with "as!".
                                                                                    – TenaciousJay
                                                                                    May 1 '15 at 16:38




                                                                                    As of Swift 1.2 downcasts can no longer be done with "as", they must be “forced failable” with "as!".
                                                                                    – TenaciousJay
                                                                                    May 1 '15 at 16:38










                                                                                    up vote
                                                                                    3
                                                                                    down vote













                                                                                                let myFirstButton = UIButton()
                                                                                    myFirstButton.setTitle("Software Button", forState: .Normal)
                                                                                    myFirstButton.setTitleColor(UIColor.redColor(), forState: .Normal)
                                                                                    myFirstButton.frame = CGRectMake(100, 300, 150, 50)
                                                                                    myFirstButton.backgroundColor = UIColor.purpleColor()
                                                                                    myFirstButton.layer.cornerRadius = 14
                                                                                    myFirstButton.addTarget(self, action: "pressed:", forControlEvents: .TouchUpInside)
                                                                                    self.view.addSubview(myFirstButton)
                                                                                    myFirstButton.hidden=true
                                                                                    nameText.delegate = self


                                                                                    func pressed(sender: UIButton!) {
                                                                                    var alertView = UIAlertView()
                                                                                    alertView.addButtonWithTitle("Ok")
                                                                                    alertView.title = "title"
                                                                                    alertView.message = "message"
                                                                                    alertView.show();
                                                                                    }





                                                                                    share|improve this answer

























                                                                                      up vote
                                                                                      3
                                                                                      down vote













                                                                                                  let myFirstButton = UIButton()
                                                                                      myFirstButton.setTitle("Software Button", forState: .Normal)
                                                                                      myFirstButton.setTitleColor(UIColor.redColor(), forState: .Normal)
                                                                                      myFirstButton.frame = CGRectMake(100, 300, 150, 50)
                                                                                      myFirstButton.backgroundColor = UIColor.purpleColor()
                                                                                      myFirstButton.layer.cornerRadius = 14
                                                                                      myFirstButton.addTarget(self, action: "pressed:", forControlEvents: .TouchUpInside)
                                                                                      self.view.addSubview(myFirstButton)
                                                                                      myFirstButton.hidden=true
                                                                                      nameText.delegate = self


                                                                                      func pressed(sender: UIButton!) {
                                                                                      var alertView = UIAlertView()
                                                                                      alertView.addButtonWithTitle("Ok")
                                                                                      alertView.title = "title"
                                                                                      alertView.message = "message"
                                                                                      alertView.show();
                                                                                      }





                                                                                      share|improve this answer























                                                                                        up vote
                                                                                        3
                                                                                        down vote










                                                                                        up vote
                                                                                        3
                                                                                        down vote









                                                                                                    let myFirstButton = UIButton()
                                                                                        myFirstButton.setTitle("Software Button", forState: .Normal)
                                                                                        myFirstButton.setTitleColor(UIColor.redColor(), forState: .Normal)
                                                                                        myFirstButton.frame = CGRectMake(100, 300, 150, 50)
                                                                                        myFirstButton.backgroundColor = UIColor.purpleColor()
                                                                                        myFirstButton.layer.cornerRadius = 14
                                                                                        myFirstButton.addTarget(self, action: "pressed:", forControlEvents: .TouchUpInside)
                                                                                        self.view.addSubview(myFirstButton)
                                                                                        myFirstButton.hidden=true
                                                                                        nameText.delegate = self


                                                                                        func pressed(sender: UIButton!) {
                                                                                        var alertView = UIAlertView()
                                                                                        alertView.addButtonWithTitle("Ok")
                                                                                        alertView.title = "title"
                                                                                        alertView.message = "message"
                                                                                        alertView.show();
                                                                                        }





                                                                                        share|improve this answer












                                                                                                    let myFirstButton = UIButton()
                                                                                        myFirstButton.setTitle("Software Button", forState: .Normal)
                                                                                        myFirstButton.setTitleColor(UIColor.redColor(), forState: .Normal)
                                                                                        myFirstButton.frame = CGRectMake(100, 300, 150, 50)
                                                                                        myFirstButton.backgroundColor = UIColor.purpleColor()
                                                                                        myFirstButton.layer.cornerRadius = 14
                                                                                        myFirstButton.addTarget(self, action: "pressed:", forControlEvents: .TouchUpInside)
                                                                                        self.view.addSubview(myFirstButton)
                                                                                        myFirstButton.hidden=true
                                                                                        nameText.delegate = self


                                                                                        func pressed(sender: UIButton!) {
                                                                                        var alertView = UIAlertView()
                                                                                        alertView.addButtonWithTitle("Ok")
                                                                                        alertView.title = "title"
                                                                                        alertView.message = "message"
                                                                                        alertView.show();
                                                                                        }






                                                                                        share|improve this answer












                                                                                        share|improve this answer



                                                                                        share|improve this answer










                                                                                        answered Oct 29 '14 at 10:31









                                                                                        abdul sathar

                                                                                        1,54411429




                                                                                        1,54411429






















                                                                                            up vote
                                                                                            3
                                                                                            down vote













                                                                                            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)


                                                                                            Selector Function is Here:



                                                                                            func buttonAction(sender:UIButton!)
                                                                                            {

                                                                                            var btnsendtag:UIButton = sender
                                                                                            if btnsendtag.tag == 22 {
                                                                                            //println("Button tapped tag 22")
                                                                                            }
                                                                                            }





                                                                                            share|improve this answer























                                                                                            • Seems like I'm running into the same issue. I initially created the button a IBAction in the storyboard, but I get "unrecognized selector sent to instance", then I delete the IBAction created that way and tried using .addTarget, they both lead to the same error.
                                                                                              – RayInNoIL
                                                                                              Aug 30 '15 at 14:34










                                                                                            • What worked for me was to delete all the IBOutlet and IBAction code in the .swift file and all the connections in InterfaceBuilder. Then re-creating everything.
                                                                                              – RayInNoIL
                                                                                              Aug 30 '15 at 16:42















                                                                                            up vote
                                                                                            3
                                                                                            down vote













                                                                                            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)


                                                                                            Selector Function is Here:



                                                                                            func buttonAction(sender:UIButton!)
                                                                                            {

                                                                                            var btnsendtag:UIButton = sender
                                                                                            if btnsendtag.tag == 22 {
                                                                                            //println("Button tapped tag 22")
                                                                                            }
                                                                                            }





                                                                                            share|improve this answer























                                                                                            • Seems like I'm running into the same issue. I initially created the button a IBAction in the storyboard, but I get "unrecognized selector sent to instance", then I delete the IBAction created that way and tried using .addTarget, they both lead to the same error.
                                                                                              – RayInNoIL
                                                                                              Aug 30 '15 at 14:34










                                                                                            • What worked for me was to delete all the IBOutlet and IBAction code in the .swift file and all the connections in InterfaceBuilder. Then re-creating everything.
                                                                                              – RayInNoIL
                                                                                              Aug 30 '15 at 16:42













                                                                                            up vote
                                                                                            3
                                                                                            down vote










                                                                                            up vote
                                                                                            3
                                                                                            down vote









                                                                                            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)


                                                                                            Selector Function is Here:



                                                                                            func buttonAction(sender:UIButton!)
                                                                                            {

                                                                                            var btnsendtag:UIButton = sender
                                                                                            if btnsendtag.tag == 22 {
                                                                                            //println("Button tapped tag 22")
                                                                                            }
                                                                                            }





                                                                                            share|improve this answer














                                                                                            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)


                                                                                            Selector Function is Here:



                                                                                            func buttonAction(sender:UIButton!)
                                                                                            {

                                                                                            var btnsendtag:UIButton = sender
                                                                                            if btnsendtag.tag == 22 {
                                                                                            //println("Button tapped tag 22")
                                                                                            }
                                                                                            }






                                                                                            share|improve this answer














                                                                                            share|improve this answer



                                                                                            share|improve this answer








                                                                                            edited Apr 1 '15 at 4:44









                                                                                            Dharmesh Kheni

                                                                                            47.9k23120146




                                                                                            47.9k23120146










                                                                                            answered Jun 23 '14 at 10:48







                                                                                            user1671097



















                                                                                            • Seems like I'm running into the same issue. I initially created the button a IBAction in the storyboard, but I get "unrecognized selector sent to instance", then I delete the IBAction created that way and tried using .addTarget, they both lead to the same error.
                                                                                              – RayInNoIL
                                                                                              Aug 30 '15 at 14:34










                                                                                            • What worked for me was to delete all the IBOutlet and IBAction code in the .swift file and all the connections in InterfaceBuilder. Then re-creating everything.
                                                                                              – RayInNoIL
                                                                                              Aug 30 '15 at 16:42


















                                                                                            • Seems like I'm running into the same issue. I initially created the button a IBAction in the storyboard, but I get "unrecognized selector sent to instance", then I delete the IBAction created that way and tried using .addTarget, they both lead to the same error.
                                                                                              – RayInNoIL
                                                                                              Aug 30 '15 at 14:34










                                                                                            • What worked for me was to delete all the IBOutlet and IBAction code in the .swift file and all the connections in InterfaceBuilder. Then re-creating everything.
                                                                                              – RayInNoIL
                                                                                              Aug 30 '15 at 16:42
















                                                                                            Seems like I'm running into the same issue. I initially created the button a IBAction in the storyboard, but I get "unrecognized selector sent to instance", then I delete the IBAction created that way and tried using .addTarget, they both lead to the same error.
                                                                                            – RayInNoIL
                                                                                            Aug 30 '15 at 14:34




                                                                                            Seems like I'm running into the same issue. I initially created the button a IBAction in the storyboard, but I get "unrecognized selector sent to instance", then I delete the IBAction created that way and tried using .addTarget, they both lead to the same error.
                                                                                            – RayInNoIL
                                                                                            Aug 30 '15 at 14:34












                                                                                            What worked for me was to delete all the IBOutlet and IBAction code in the .swift file and all the connections in InterfaceBuilder. Then re-creating everything.
                                                                                            – RayInNoIL
                                                                                            Aug 30 '15 at 16:42




                                                                                            What worked for me was to delete all the IBOutlet and IBAction code in the .swift file and all the connections in InterfaceBuilder. Then re-creating everything.
                                                                                            – RayInNoIL
                                                                                            Aug 30 '15 at 16:42










                                                                                            up vote
                                                                                            1
                                                                                            down vote














                                                                                            This works for me very well, #DynamicButtonEvent #IOS #Swift #Xcode




                                                                                            func setupButtonMap(){
                                                                                            let mapButton = UIButton(type: .system)
                                                                                            mapButton.setImage(#imageLiteral(resourceName: "CreateTrip").withRenderingMode(.alwaysOriginal), for: .normal)
                                                                                            mapButton.frame = CGRect(x: 0, y: 0, width: 34, height: 34)
                                                                                            mapButton.contentMode = .scaleAspectFit
                                                                                            mapButton.backgroundColor = UIColor.clear
                                                                                            mapButton.addTarget(self, action: #selector(ViewController.btnOpenMap(_:)), for: .touchUpInside)
                                                                                            navigationItem.leftBarButtonItem = UIBarButtonItem(customView: mapButton)
                                                                                            }
                                                                                            @IBAction func btnOpenMap(_ sender: Any?) {
                                                                                            print("Successful")
                                                                                            }





                                                                                            share|improve this answer

























                                                                                              up vote
                                                                                              1
                                                                                              down vote














                                                                                              This works for me very well, #DynamicButtonEvent #IOS #Swift #Xcode




                                                                                              func setupButtonMap(){
                                                                                              let mapButton = UIButton(type: .system)
                                                                                              mapButton.setImage(#imageLiteral(resourceName: "CreateTrip").withRenderingMode(.alwaysOriginal), for: .normal)
                                                                                              mapButton.frame = CGRect(x: 0, y: 0, width: 34, height: 34)
                                                                                              mapButton.contentMode = .scaleAspectFit
                                                                                              mapButton.backgroundColor = UIColor.clear
                                                                                              mapButton.addTarget(self, action: #selector(ViewController.btnOpenMap(_:)), for: .touchUpInside)
                                                                                              navigationItem.leftBarButtonItem = UIBarButtonItem(customView: mapButton)
                                                                                              }
                                                                                              @IBAction func btnOpenMap(_ sender: Any?) {
                                                                                              print("Successful")
                                                                                              }





                                                                                              share|improve this answer























                                                                                                up vote
                                                                                                1
                                                                                                down vote










                                                                                                up vote
                                                                                                1
                                                                                                down vote










                                                                                                This works for me very well, #DynamicButtonEvent #IOS #Swift #Xcode




                                                                                                func setupButtonMap(){
                                                                                                let mapButton = UIButton(type: .system)
                                                                                                mapButton.setImage(#imageLiteral(resourceName: "CreateTrip").withRenderingMode(.alwaysOriginal), for: .normal)
                                                                                                mapButton.frame = CGRect(x: 0, y: 0, width: 34, height: 34)
                                                                                                mapButton.contentMode = .scaleAspectFit
                                                                                                mapButton.backgroundColor = UIColor.clear
                                                                                                mapButton.addTarget(self, action: #selector(ViewController.btnOpenMap(_:)), for: .touchUpInside)
                                                                                                navigationItem.leftBarButtonItem = UIBarButtonItem(customView: mapButton)
                                                                                                }
                                                                                                @IBAction func btnOpenMap(_ sender: Any?) {
                                                                                                print("Successful")
                                                                                                }





                                                                                                share|improve this answer













                                                                                                This works for me very well, #DynamicButtonEvent #IOS #Swift #Xcode




                                                                                                func setupButtonMap(){
                                                                                                let mapButton = UIButton(type: .system)
                                                                                                mapButton.setImage(#imageLiteral(resourceName: "CreateTrip").withRenderingMode(.alwaysOriginal), for: .normal)
                                                                                                mapButton.frame = CGRect(x: 0, y: 0, width: 34, height: 34)
                                                                                                mapButton.contentMode = .scaleAspectFit
                                                                                                mapButton.backgroundColor = UIColor.clear
                                                                                                mapButton.addTarget(self, action: #selector(ViewController.btnOpenMap(_:)), for: .touchUpInside)
                                                                                                navigationItem.leftBarButtonItem = UIBarButtonItem(customView: mapButton)
                                                                                                }
                                                                                                @IBAction func btnOpenMap(_ sender: Any?) {
                                                                                                print("Successful")
                                                                                                }






                                                                                                share|improve this answer












                                                                                                share|improve this answer



                                                                                                share|improve this answer










                                                                                                answered May 29 at 16:07









                                                                                                Lex

                                                                                                214




                                                                                                214






















                                                                                                    up vote
                                                                                                    0
                                                                                                    down vote













                                                                                                    Swift: Ui Button create programmatically



                                                                                                    let myButton = UIButton()

                                                                                                    myButton.titleLabel!.frame = CGRectMake(15, 54, 300, 500)
                                                                                                    myButton.titleLabel!.text = "Button Label"
                                                                                                    myButton.titleLabel!.textColor = UIColor.redColor()
                                                                                                    myButton.titleLabel!.textAlignment = .Center
                                                                                                    self.view.addSubview(myButton)





                                                                                                    share|improve this answer



























                                                                                                      up vote
                                                                                                      0
                                                                                                      down vote













                                                                                                      Swift: Ui Button create programmatically



                                                                                                      let myButton = UIButton()

                                                                                                      myButton.titleLabel!.frame = CGRectMake(15, 54, 300, 500)
                                                                                                      myButton.titleLabel!.text = "Button Label"
                                                                                                      myButton.titleLabel!.textColor = UIColor.redColor()
                                                                                                      myButton.titleLabel!.textAlignment = .Center
                                                                                                      self.view.addSubview(myButton)





                                                                                                      share|improve this answer

























                                                                                                        up vote
                                                                                                        0
                                                                                                        down vote










                                                                                                        up vote
                                                                                                        0
                                                                                                        down vote









                                                                                                        Swift: Ui Button create programmatically



                                                                                                        let myButton = UIButton()

                                                                                                        myButton.titleLabel!.frame = CGRectMake(15, 54, 300, 500)
                                                                                                        myButton.titleLabel!.text = "Button Label"
                                                                                                        myButton.titleLabel!.textColor = UIColor.redColor()
                                                                                                        myButton.titleLabel!.textAlignment = .Center
                                                                                                        self.view.addSubview(myButton)





                                                                                                        share|improve this answer














                                                                                                        Swift: Ui Button create programmatically



                                                                                                        let myButton = UIButton()

                                                                                                        myButton.titleLabel!.frame = CGRectMake(15, 54, 300, 500)
                                                                                                        myButton.titleLabel!.text = "Button Label"
                                                                                                        myButton.titleLabel!.textColor = UIColor.redColor()
                                                                                                        myButton.titleLabel!.textAlignment = .Center
                                                                                                        self.view.addSubview(myButton)






                                                                                                        share|improve this answer














                                                                                                        share|improve this answer



                                                                                                        share|improve this answer








                                                                                                        edited Apr 23 '15 at 7:38

























                                                                                                        answered Apr 23 '15 at 7:31









                                                                                                        Shanmugasundharam selvadurai

                                                                                                        1,5771627




                                                                                                        1,5771627






















                                                                                                            up vote
                                                                                                            0
                                                                                                            down vote













                                                                                                            Uilabel code 

                                                                                                            var label: UILabel = UILabel()
                                                                                                            label.frame = CGRectMake(50, 50, 200, 21)
                                                                                                            label.backgroundColor = UIColor.blackColor()
                                                                                                            label.textColor = UIColor.whiteColor()
                                                                                                            label.textAlignment = NSTextAlignment.Center
                                                                                                            label.text = "test label"
                                                                                                            self.view.addSubview(label)





                                                                                                            share|improve this answer

















                                                                                                            • 2




                                                                                                              It is always advised to add some explanation to your code
                                                                                                              – Bowdzone
                                                                                                              May 26 '15 at 10:30















                                                                                                            up vote
                                                                                                            0
                                                                                                            down vote













                                                                                                            Uilabel code 

                                                                                                            var label: UILabel = UILabel()
                                                                                                            label.frame = CGRectMake(50, 50, 200, 21)
                                                                                                            label.backgroundColor = UIColor.blackColor()
                                                                                                            label.textColor = UIColor.whiteColor()
                                                                                                            label.textAlignment = NSTextAlignment.Center
                                                                                                            label.text = "test label"
                                                                                                            self.view.addSubview(label)





                                                                                                            share|improve this answer

















                                                                                                            • 2




                                                                                                              It is always advised to add some explanation to your code
                                                                                                              – Bowdzone
                                                                                                              May 26 '15 at 10:30













                                                                                                            up vote
                                                                                                            0
                                                                                                            down vote










                                                                                                            up vote
                                                                                                            0
                                                                                                            down vote









                                                                                                            Uilabel code 

                                                                                                            var label: UILabel = UILabel()
                                                                                                            label.frame = CGRectMake(50, 50, 200, 21)
                                                                                                            label.backgroundColor = UIColor.blackColor()
                                                                                                            label.textColor = UIColor.whiteColor()
                                                                                                            label.textAlignment = NSTextAlignment.Center
                                                                                                            label.text = "test label"
                                                                                                            self.view.addSubview(label)





                                                                                                            share|improve this answer












                                                                                                            Uilabel code 

                                                                                                            var label: UILabel = UILabel()
                                                                                                            label.frame = CGRectMake(50, 50, 200, 21)
                                                                                                            label.backgroundColor = UIColor.blackColor()
                                                                                                            label.textColor = UIColor.whiteColor()
                                                                                                            label.textAlignment = NSTextAlignment.Center
                                                                                                            label.text = "test label"
                                                                                                            self.view.addSubview(label)






                                                                                                            share|improve this answer












                                                                                                            share|improve this answer



                                                                                                            share|improve this answer










                                                                                                            answered May 26 '15 at 10:00









                                                                                                            varun

                                                                                                            1




                                                                                                            1








                                                                                                            • 2




                                                                                                              It is always advised to add some explanation to your code
                                                                                                              – Bowdzone
                                                                                                              May 26 '15 at 10:30














                                                                                                            • 2




                                                                                                              It is always advised to add some explanation to your code
                                                                                                              – Bowdzone
                                                                                                              May 26 '15 at 10:30








                                                                                                            2




                                                                                                            2




                                                                                                            It is always advised to add some explanation to your code
                                                                                                            – Bowdzone
                                                                                                            May 26 '15 at 10:30




                                                                                                            It is always advised to add some explanation to your code
                                                                                                            – Bowdzone
                                                                                                            May 26 '15 at 10:30










                                                                                                            up vote
                                                                                                            0
                                                                                                            down vote













                                                                                                                // UILabel:
                                                                                                            let label = UILabel()
                                                                                                            label.frame = CGRectMake(35, 100, 250, 30)
                                                                                                            label.textColor = UIColor.blackColor()
                                                                                                            label.textAlignment = NSTextAlignment.Center
                                                                                                            label.text = "Hello World"
                                                                                                            self.view.addSubview(label)

                                                                                                            // UIButton:
                                                                                                            let btn: UIButton = UIButton(type: UIButtonType.Custom) as UIButton
                                                                                                            btn.frame = CGRectMake(130, 70, 60, 20)
                                                                                                            btn.setTitle("Click", forState: UIControlState.Normal)
                                                                                                            btn.setTitleColor(UIColor.blackColor(), forState: .Normal)
                                                                                                            btn.addTarget(self, action:Selector("clickAction"), forControlEvents: UIControlEvents.TouchUpInside)
                                                                                                            view.addSubview(btn)


                                                                                                            // Button Action:
                                                                                                            @IBAction func clickAction(sender:AnyObject)
                                                                                                            {
                                                                                                            print("Click Action")
                                                                                                            }





                                                                                                            share|improve this answer

























                                                                                                              up vote
                                                                                                              0
                                                                                                              down vote













                                                                                                                  // UILabel:
                                                                                                              let label = UILabel()
                                                                                                              label.frame = CGRectMake(35, 100, 250, 30)
                                                                                                              label.textColor = UIColor.blackColor()
                                                                                                              label.textAlignment = NSTextAlignment.Center
                                                                                                              label.text = "Hello World"
                                                                                                              self.view.addSubview(label)

                                                                                                              // UIButton:
                                                                                                              let btn: UIButton = UIButton(type: UIButtonType.Custom) as UIButton
                                                                                                              btn.frame = CGRectMake(130, 70, 60, 20)
                                                                                                              btn.setTitle("Click", forState: UIControlState.Normal)
                                                                                                              btn.setTitleColor(UIColor.blackColor(), forState: .Normal)
                                                                                                              btn.addTarget(self, action:Selector("clickAction"), forControlEvents: UIControlEvents.TouchUpInside)
                                                                                                              view.addSubview(btn)


                                                                                                              // Button Action:
                                                                                                              @IBAction func clickAction(sender:AnyObject)
                                                                                                              {
                                                                                                              print("Click Action")
                                                                                                              }





                                                                                                              share|improve this answer























                                                                                                                up vote
                                                                                                                0
                                                                                                                down vote










                                                                                                                up vote
                                                                                                                0
                                                                                                                down vote









                                                                                                                    // UILabel:
                                                                                                                let label = UILabel()
                                                                                                                label.frame = CGRectMake(35, 100, 250, 30)
                                                                                                                label.textColor = UIColor.blackColor()
                                                                                                                label.textAlignment = NSTextAlignment.Center
                                                                                                                label.text = "Hello World"
                                                                                                                self.view.addSubview(label)

                                                                                                                // UIButton:
                                                                                                                let btn: UIButton = UIButton(type: UIButtonType.Custom) as UIButton
                                                                                                                btn.frame = CGRectMake(130, 70, 60, 20)
                                                                                                                btn.setTitle("Click", forState: UIControlState.Normal)
                                                                                                                btn.setTitleColor(UIColor.blackColor(), forState: .Normal)
                                                                                                                btn.addTarget(self, action:Selector("clickAction"), forControlEvents: UIControlEvents.TouchUpInside)
                                                                                                                view.addSubview(btn)


                                                                                                                // Button Action:
                                                                                                                @IBAction func clickAction(sender:AnyObject)
                                                                                                                {
                                                                                                                print("Click Action")
                                                                                                                }





                                                                                                                share|improve this answer












                                                                                                                    // UILabel:
                                                                                                                let label = UILabel()
                                                                                                                label.frame = CGRectMake(35, 100, 250, 30)
                                                                                                                label.textColor = UIColor.blackColor()
                                                                                                                label.textAlignment = NSTextAlignment.Center
                                                                                                                label.text = "Hello World"
                                                                                                                self.view.addSubview(label)

                                                                                                                // UIButton:
                                                                                                                let btn: UIButton = UIButton(type: UIButtonType.Custom) as UIButton
                                                                                                                btn.frame = CGRectMake(130, 70, 60, 20)
                                                                                                                btn.setTitle("Click", forState: UIControlState.Normal)
                                                                                                                btn.setTitleColor(UIColor.blackColor(), forState: .Normal)
                                                                                                                btn.addTarget(self, action:Selector("clickAction"), forControlEvents: UIControlEvents.TouchUpInside)
                                                                                                                view.addSubview(btn)


                                                                                                                // Button Action:
                                                                                                                @IBAction func clickAction(sender:AnyObject)
                                                                                                                {
                                                                                                                print("Click Action")
                                                                                                                }






                                                                                                                share|improve this answer












                                                                                                                share|improve this answer



                                                                                                                share|improve this answer










                                                                                                                answered Oct 3 '16 at 10:38









                                                                                                                The King

                                                                                                                92




                                                                                                                92






















                                                                                                                    up vote
                                                                                                                    0
                                                                                                                    down vote













                                                                                                                    Step 1: Make a new project



                                                                                                                    enter image description here



                                                                                                                    Step 2: in ViewController.swift



                                                                                                                    import UIKit

                                                                                                                    class ViewController: UIViewController {

                                                                                                                    override func viewDidLoad() {
                                                                                                                    super.viewDidLoad()

                                                                                                                    // CODE
                                                                                                                    let btn = UIButton(type: UIButtonType.System) as UIButton
                                                                                                                    btn.backgroundColor = UIColor.blueColor()
                                                                                                                    btn.setTitle("CALL TPT AGENT", forState: UIControlState.Normal)
                                                                                                                    btn.frame = CGRectMake(100, 100, 200, 100)
                                                                                                                    btn.addTarget(self, action: "clickMe:", forControlEvents: UIControlEvents.TouchUpInside)
                                                                                                                    self.view.addSubview(btn)

                                                                                                                    }

                                                                                                                    func clickMe(sender:UIButton!) {
                                                                                                                    print("CALL")
                                                                                                                    }

                                                                                                                    override func didReceiveMemoryWarning() {
                                                                                                                    super.didReceiveMemoryWarning()
                                                                                                                    // Dispose of any resources that can be recreated.
                                                                                                                    }


                                                                                                                    }





                                                                                                                    share|improve this answer

























                                                                                                                      up vote
                                                                                                                      0
                                                                                                                      down vote













                                                                                                                      Step 1: Make a new project



                                                                                                                      enter image description here



                                                                                                                      Step 2: in ViewController.swift



                                                                                                                      import UIKit

                                                                                                                      class ViewController: UIViewController {

                                                                                                                      override func viewDidLoad() {
                                                                                                                      super.viewDidLoad()

                                                                                                                      // CODE
                                                                                                                      let btn = UIButton(type: UIButtonType.System) as UIButton
                                                                                                                      btn.backgroundColor = UIColor.blueColor()
                                                                                                                      btn.setTitle("CALL TPT AGENT", forState: UIControlState.Normal)
                                                                                                                      btn.frame = CGRectMake(100, 100, 200, 100)
                                                                                                                      btn.addTarget(self, action: "clickMe:", forControlEvents: UIControlEvents.TouchUpInside)
                                                                                                                      self.view.addSubview(btn)

                                                                                                                      }

                                                                                                                      func clickMe(sender:UIButton!) {
                                                                                                                      print("CALL")
                                                                                                                      }

                                                                                                                      override func didReceiveMemoryWarning() {
                                                                                                                      super.didReceiveMemoryWarning()
                                                                                                                      // Dispose of any resources that can be recreated.
                                                                                                                      }


                                                                                                                      }





                                                                                                                      share|improve this answer























                                                                                                                        up vote
                                                                                                                        0
                                                                                                                        down vote










                                                                                                                        up vote
                                                                                                                        0
                                                                                                                        down vote









                                                                                                                        Step 1: Make a new project



                                                                                                                        enter image description here



                                                                                                                        Step 2: in ViewController.swift



                                                                                                                        import UIKit

                                                                                                                        class ViewController: UIViewController {

                                                                                                                        override func viewDidLoad() {
                                                                                                                        super.viewDidLoad()

                                                                                                                        // CODE
                                                                                                                        let btn = UIButton(type: UIButtonType.System) as UIButton
                                                                                                                        btn.backgroundColor = UIColor.blueColor()
                                                                                                                        btn.setTitle("CALL TPT AGENT", forState: UIControlState.Normal)
                                                                                                                        btn.frame = CGRectMake(100, 100, 200, 100)
                                                                                                                        btn.addTarget(self, action: "clickMe:", forControlEvents: UIControlEvents.TouchUpInside)
                                                                                                                        self.view.addSubview(btn)

                                                                                                                        }

                                                                                                                        func clickMe(sender:UIButton!) {
                                                                                                                        print("CALL")
                                                                                                                        }

                                                                                                                        override func didReceiveMemoryWarning() {
                                                                                                                        super.didReceiveMemoryWarning()
                                                                                                                        // Dispose of any resources that can be recreated.
                                                                                                                        }


                                                                                                                        }





                                                                                                                        share|improve this answer












                                                                                                                        Step 1: Make a new project



                                                                                                                        enter image description here



                                                                                                                        Step 2: in ViewController.swift



                                                                                                                        import UIKit

                                                                                                                        class ViewController: UIViewController {

                                                                                                                        override func viewDidLoad() {
                                                                                                                        super.viewDidLoad()

                                                                                                                        // CODE
                                                                                                                        let btn = UIButton(type: UIButtonType.System) as UIButton
                                                                                                                        btn.backgroundColor = UIColor.blueColor()
                                                                                                                        btn.setTitle("CALL TPT AGENT", forState: UIControlState.Normal)
                                                                                                                        btn.frame = CGRectMake(100, 100, 200, 100)
                                                                                                                        btn.addTarget(self, action: "clickMe:", forControlEvents: UIControlEvents.TouchUpInside)
                                                                                                                        self.view.addSubview(btn)

                                                                                                                        }

                                                                                                                        func clickMe(sender:UIButton!) {
                                                                                                                        print("CALL")
                                                                                                                        }

                                                                                                                        override func didReceiveMemoryWarning() {
                                                                                                                        super.didReceiveMemoryWarning()
                                                                                                                        // Dispose of any resources that can be recreated.
                                                                                                                        }


                                                                                                                        }






                                                                                                                        share|improve this answer












                                                                                                                        share|improve this answer



                                                                                                                        share|improve this answer










                                                                                                                        answered Oct 14 '16 at 11:18









                                                                                                                        YumYumYum

                                                                                                                        9,27637159296




                                                                                                                        9,27637159296






















                                                                                                                            up vote
                                                                                                                            0
                                                                                                                            down vote













                                                                                                                            enter image description here



                                                                                                                             func viewDidLoad(){
                                                                                                                            saveActionButton = UIButton(frame: CGRect(x: self.view.frame.size.width - 60, y: 0, width: 50, height: 50))
                                                                                                                            self.saveActionButton.backgroundColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 0.7)
                                                                                                                            saveActionButton.addTarget(self, action: #selector(doneAction), for: .touchUpInside)
                                                                                                                            self.saveActionButton.setTitle("Done", for: .normal)
                                                                                                                            self.saveActionButton.layer.cornerRadius = self.saveActionButton.frame.size.width / 2
                                                                                                                            self.saveActionButton.layer.borderColor = UIColor.darkGray.cgColor
                                                                                                                            self.saveActionButton.layer.borderWidth = 1
                                                                                                                            self.saveActionButton.center.y = self.view.frame.size.height - 80
                                                                                                                            self.view.addSubview(saveActionButton)
                                                                                                                            }

                                                                                                                            func doneAction(){
                                                                                                                            print("Write your own logic")
                                                                                                                            }





                                                                                                                            share|improve this answer



























                                                                                                                              up vote
                                                                                                                              0
                                                                                                                              down vote













                                                                                                                              enter image description here



                                                                                                                               func viewDidLoad(){
                                                                                                                              saveActionButton = UIButton(frame: CGRect(x: self.view.frame.size.width - 60, y: 0, width: 50, height: 50))
                                                                                                                              self.saveActionButton.backgroundColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 0.7)
                                                                                                                              saveActionButton.addTarget(self, action: #selector(doneAction), for: .touchUpInside)
                                                                                                                              self.saveActionButton.setTitle("Done", for: .normal)
                                                                                                                              self.saveActionButton.layer.cornerRadius = self.saveActionButton.frame.size.width / 2
                                                                                                                              self.saveActionButton.layer.borderColor = UIColor.darkGray.cgColor
                                                                                                                              self.saveActionButton.layer.borderWidth = 1
                                                                                                                              self.saveActionButton.center.y = self.view.frame.size.height - 80
                                                                                                                              self.view.addSubview(saveActionButton)
                                                                                                                              }

                                                                                                                              func doneAction(){
                                                                                                                              print("Write your own logic")
                                                                                                                              }





                                                                                                                              share|improve this answer

























                                                                                                                                up vote
                                                                                                                                0
                                                                                                                                down vote










                                                                                                                                up vote
                                                                                                                                0
                                                                                                                                down vote









                                                                                                                                enter image description here



                                                                                                                                 func viewDidLoad(){
                                                                                                                                saveActionButton = UIButton(frame: CGRect(x: self.view.frame.size.width - 60, y: 0, width: 50, height: 50))
                                                                                                                                self.saveActionButton.backgroundColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 0.7)
                                                                                                                                saveActionButton.addTarget(self, action: #selector(doneAction), for: .touchUpInside)
                                                                                                                                self.saveActionButton.setTitle("Done", for: .normal)
                                                                                                                                self.saveActionButton.layer.cornerRadius = self.saveActionButton.frame.size.width / 2
                                                                                                                                self.saveActionButton.layer.borderColor = UIColor.darkGray.cgColor
                                                                                                                                self.saveActionButton.layer.borderWidth = 1
                                                                                                                                self.saveActionButton.center.y = self.view.frame.size.height - 80
                                                                                                                                self.view.addSubview(saveActionButton)
                                                                                                                                }

                                                                                                                                func doneAction(){
                                                                                                                                print("Write your own logic")
                                                                                                                                }





                                                                                                                                share|improve this answer














                                                                                                                                enter image description here



                                                                                                                                 func viewDidLoad(){
                                                                                                                                saveActionButton = UIButton(frame: CGRect(x: self.view.frame.size.width - 60, y: 0, width: 50, height: 50))
                                                                                                                                self.saveActionButton.backgroundColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 0.7)
                                                                                                                                saveActionButton.addTarget(self, action: #selector(doneAction), for: .touchUpInside)
                                                                                                                                self.saveActionButton.setTitle("Done", for: .normal)
                                                                                                                                self.saveActionButton.layer.cornerRadius = self.saveActionButton.frame.size.width / 2
                                                                                                                                self.saveActionButton.layer.borderColor = UIColor.darkGray.cgColor
                                                                                                                                self.saveActionButton.layer.borderWidth = 1
                                                                                                                                self.saveActionButton.center.y = self.view.frame.size.height - 80
                                                                                                                                self.view.addSubview(saveActionButton)
                                                                                                                                }

                                                                                                                                func doneAction(){
                                                                                                                                print("Write your own logic")
                                                                                                                                }






                                                                                                                                share|improve this answer














                                                                                                                                share|improve this answer



                                                                                                                                share|improve this answer








                                                                                                                                edited Aug 17 '17 at 6:03

























                                                                                                                                answered Aug 17 '17 at 5:55









                                                                                                                                Sai kumar Reddy

                                                                                                                                56739




                                                                                                                                56739






















                                                                                                                                    up vote
                                                                                                                                    -1
                                                                                                                                    down vote













                                                                                                                                    override func viewDidLoad() {

                                                                                                                                    super.viewDidLoad()
                                                                                                                                    // Do any additional setup after loading the view, typically from a nib.

                                                                                                                                    var imageView = UIImageView(frame: CGRectMake(100, 150, 150, 150));
                                                                                                                                    var image = UIImage(named: "BattleMapSplashScreen.png");
                                                                                                                                    imageView.image = image;
                                                                                                                                    self.view.addSubview(imageView);

                                                                                                                                    }





                                                                                                                                    share|improve this answer



























                                                                                                                                      up vote
                                                                                                                                      -1
                                                                                                                                      down vote













                                                                                                                                      override func viewDidLoad() {

                                                                                                                                      super.viewDidLoad()
                                                                                                                                      // Do any additional setup after loading the view, typically from a nib.

                                                                                                                                      var imageView = UIImageView(frame: CGRectMake(100, 150, 150, 150));
                                                                                                                                      var image = UIImage(named: "BattleMapSplashScreen.png");
                                                                                                                                      imageView.image = image;
                                                                                                                                      self.view.addSubview(imageView);

                                                                                                                                      }





                                                                                                                                      share|improve this answer

























                                                                                                                                        up vote
                                                                                                                                        -1
                                                                                                                                        down vote










                                                                                                                                        up vote
                                                                                                                                        -1
                                                                                                                                        down vote









                                                                                                                                        override func viewDidLoad() {

                                                                                                                                        super.viewDidLoad()
                                                                                                                                        // Do any additional setup after loading the view, typically from a nib.

                                                                                                                                        var imageView = UIImageView(frame: CGRectMake(100, 150, 150, 150));
                                                                                                                                        var image = UIImage(named: "BattleMapSplashScreen.png");
                                                                                                                                        imageView.image = image;
                                                                                                                                        self.view.addSubview(imageView);

                                                                                                                                        }





                                                                                                                                        share|improve this answer














                                                                                                                                        override func viewDidLoad() {

                                                                                                                                        super.viewDidLoad()
                                                                                                                                        // Do any additional setup after loading the view, typically from a nib.

                                                                                                                                        var imageView = UIImageView(frame: CGRectMake(100, 150, 150, 150));
                                                                                                                                        var image = UIImage(named: "BattleMapSplashScreen.png");
                                                                                                                                        imageView.image = image;
                                                                                                                                        self.view.addSubview(imageView);

                                                                                                                                        }






                                                                                                                                        share|improve this answer














                                                                                                                                        share|improve this answer



                                                                                                                                        share|improve this answer








                                                                                                                                        edited Apr 1 '15 at 4:44









                                                                                                                                        Dharmesh Kheni

                                                                                                                                        47.9k23120146




                                                                                                                                        47.9k23120146










                                                                                                                                        answered Aug 19 '14 at 16:24









                                                                                                                                        Durgesh

                                                                                                                                        11




                                                                                                                                        11






























                                                                                                                                            draft saved

                                                                                                                                            draft discarded




















































                                                                                                                                            Thanks for contributing an answer to Stack Overflow!


                                                                                                                                            • Please be sure to answer the question. Provide details and share your research!

                                                                                                                                            But avoid



                                                                                                                                            • Asking for help, clarification, or responding to other answers.

                                                                                                                                            • Making statements based on opinion; back them up with references or personal experience.


                                                                                                                                            To learn more, see our tips on writing great answers.





                                                                                                                                            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                                                                                                                            Please pay close attention to the following guidance:


                                                                                                                                            • Please be sure to answer the question. Provide details and share your research!

                                                                                                                                            But avoid



                                                                                                                                            • Asking for help, clarification, or responding to other answers.

                                                                                                                                            • Making statements based on opinion; back them up with references or personal experience.


                                                                                                                                            To learn more, see our tips on writing great answers.




                                                                                                                                            draft saved


                                                                                                                                            draft discarded














                                                                                                                                            StackExchange.ready(
                                                                                                                                            function () {
                                                                                                                                            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f24030348%2fhow-to-create-a-button-programmatically%23new-answer', 'question_page');
                                                                                                                                            }
                                                                                                                                            );

                                                                                                                                            Post as a guest















                                                                                                                                            Required, but never shown





















































                                                                                                                                            Required, but never shown














                                                                                                                                            Required, but never shown












                                                                                                                                            Required, but never shown







                                                                                                                                            Required, but never shown

































                                                                                                                                            Required, but never shown














                                                                                                                                            Required, but never shown












                                                                                                                                            Required, but never shown







                                                                                                                                            Required, but never shown







                                                                                                                                            Popular posts from this blog

                                                                                                                                            Trompette piccolo

                                                                                                                                            Slow SSRS Report in dynamic grouping and multiple parameters

                                                                                                                                            Simon Yates (cyclisme)