Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set button type

I am creating a button programatically and I would like to know how to set that button's UIButtonType.

This is how I am creating my button:

let headerPlusButon:UIButton = UIButton(frame: CGRectMake(5, tableView.frame.width - 30, 20, 20))
headerPlusButon.addTarget(self, action: "paymentAddButtonTapped", forControlEvents:.TouchUpInside)

There is no "setButtonTypeFor..." method like how you would change the title's text and obviously this doesn't work:

headerPlusButon.buttonType = UIButtonType.ContactAdd
like image 980
Petri Avatar asked Jan 09 '15 09:01

Petri


2 Answers

override func viewDidLoad() {

    super.viewDidLoad()

    let button   = UIButton.buttonWithType(UIButtonType.System) as UIButton
    button.frame = CGRectMake(100, 100, 100, 50)
    button.backgroundColor = UIColor.greenColor()
    button.setTitle("Test Button", forState: UIControlState.Normal)
    button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)

    self.view.addSubview(button)
}  

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

from swift 2 replace UIButton declaration with below line.

let button = UIButton(type: .System) as UIButton
like image 174
Abhishek Sharma Avatar answered Oct 27 '22 09:10

Abhishek Sharma


Here is my code

let tutorialButton = UIButton.init(type: .infoDark)
        tutorialButton.frame = CGRect(x: self.view.frame.size.width - 20, y: 42, width: 20, height: 20)
        tutorialButton.addTarget(self, action: #selector(self.showTutorial), for: .touchUpInside)
        
        view.addSubview(tutorialButton)

I hope it can help you!

like image 32
Dx_ Avatar answered Oct 27 '22 10:10

Dx_