By val_lek


2014-06-04 06:18:37 8 Comments

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.

22 comments

@Museer Ahamad Ansari 2016-11-02 12:38:48

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("your Button Name", 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")
 }

@J.C 2017-03-30 15:40:08

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)

@Ruslan Leshchenko 2018-03-19 08:10:26

In Swift 4 before "func" need to add "@objc".

@Parth 2019-01-16 12:00:56

Write this sample code in Swift 4.2 for add Button Programmatically.

override func viewDidLoad() {
    super.viewDidLoad()
        let myButton = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
        myButton.backgroundColor = .green
        myButton.setTitle("Hello UIButton", for: .normal)
        myButton.addTarget(self, action: #selector(myButtonAction), for: .touchUpInside)
        self.view.addSubview(myButton)
}

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

@Anil Varghese 2014-06-04 08:39:14

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.

@Alexey Globchastyy 2014-07-20 07:54:26

and don't forget that your target class should be derived from NSObject

@Pablo Zbigy Jablonski 2014-11-20 23:00:13

and dont forget that the function that is your action cannot be private

@Ixx 2014-12-08 21:26:36

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 :(

@DeveloperACE 2015-01-27 21:05:31

Is there any way to change a buttons corner radius?

@Kevin Qi 2015-04-16 19:07:10

As of Xcode 6.3, having the colon after buttonAction in button.addTarget(self, action: "buttonAction:", ...) will result in an "unrecognized selector" runtime error. Removing the colon fixes the issue.

@TenaciousJay 2015-05-01 16:38:08

As of Swift 1.2 downcasts can no longer be done with "as", they must be “forced failable” with "as!".

@Nikola Lukic 2016-08-26 13:52:12

What about swift 3 , not working any of this code .... ???

@Justin Oroz 2017-09-05 17:00:11

The button would not show up without assigning buttonType

@kiran 2018-11-25 16:08:34

Why need to add @objc at button action ? your answer will helps me to understand a bit more.

@Colin Hancey 2019-01-31 01:36:19

How can a function be called inside of the buttonAction in Swift 4? I seem to be able to call my function in the ViewController, but not inside the buttonAction

@Lex 2018-05-29 16:07:03

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")
}

@Akhtar 2014-06-06 13:21:04

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.

@zumzum 2014-06-13 22:32:36

so, why do you need the "as" operator in the first line of code you shared before UIButton...?

@Chris C 2014-09-19 13:07:29

buttonWithType returns type AnyObject, so you need to cast it as a UIButton

@Akhtar 2014-09-25 12:06:49

@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.

@TenaciousJay 2015-05-01 16:38:27

As of Swift 1.2 downcasts can no longer be done with "as", they must be “forced failable” with "as!".

@n.by.n 2016-03-30 12:27:57

For people who run into Objective C String literals deprecated warnings Correct answer is here: stackoverflow.com/a/36308587/968848

@Dharmbir Singh 2014-06-04 07:08:47

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")
}

@val_lek 2014-06-04 07:26:02

sorry, but the compiler sent error in line - self.view.addSubview(view: myButton). Error is next: "Extraneous argument label 'view:' in call"

@Dharmbir Singh 2014-06-04 07:26:55

Please remove this line self.view.addSubview(view: myButton) For more info see my edited answer.

@val_lek 2014-06-04 07:31:00

Thank you, but how I can add this button on self.view?

@Sai kumar Reddy 2017-08-17 05:55:41

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")
         }

@user3182143 2015-10-08 12:33:27

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

@Felipe 2015-10-27 18:13:52

Thanks, m8! Starting up with Swift today so everything is kind of strange (:

@CodeBender 2016-10-19 19:04:33

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")
}

@YumYumYum 2016-10-14 11:18:03

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.
    }


}

@The King 2016-10-03 10:38:00

    // 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")
    }

@Cezary Wojcik 2014-06-04 06:25:26

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

@A.G 2016-03-22 06:41:31

 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")

 }

@Muhammad Qasim 2016-01-29 06:28:22

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)

@varun 2015-05-26 10:00:48

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)

@Bowdzone 2015-05-26 10:30:32

It is always advised to add some explanation to your code

@Nimmy Alphonsa Jose 2015-05-13 10:05:32

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")
}

@Shanmugasundharam 2015-04-23 07:31:48

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)

@user1671097 2014-06-23 10:48:06

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")
    }
}

@RayInNoIL 2015-08-30 14:34: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 2015-08-30 16:42:23

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.

@Durgesh 2014-08-19 16:24:56

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);

}

@abdul sathar 2014-10-29 10:31:44

            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();
    }

@Alessandro Pirovano 2014-09-04 10:08:25

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")
}

@TenaciousJay 2015-05-01 16:38:47

As of Swift 1.2 downcasts can no longer be done with "as", they must be “forced failable” with "as!".

@Connor 2014-06-04 06:22:45

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))

Related Questions

Sponsored Content

34 Answered Questions

[SOLVED] How do I create a basic UIButton programmatically?

12 Answered Questions

[SOLVED] How do I concatenate or merge arrays in Swift?

16 Answered Questions

[SOLVED] How to check if an element is in an array

  • 2014-06-08 00:52:11
  • jaredsmith
  • 323381 View
  • 433 Score
  • 16 Answer
  • Tags:   arrays swift

5 Answered Questions

[SOLVED] How can I change UIButton title color?

12 Answered Questions

[SOLVED] How to create UILabel programmatically using Swift?

  • 2014-06-06 12:21:12
  • Akhtar
  • 165329 View
  • 104 Score
  • 12 Answer
  • Tags:   ios swift

31 Answered Questions

[SOLVED] Using a dispatch_once singleton model in Swift

22 Answered Questions

[SOLVED] iOS app with framework crashed on device, dyld: Library not loaded, Xcode 6 Beta

34 Answered Questions

[SOLVED] UIButton: Making the hit area larger than the default hit area

9 Answered Questions

[SOLVED] Swift Beta performance: sorting arrays

2 Answered Questions

Sponsored Content