Set button type

2019-05-18 18:29发布

问题:

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

回答1:

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


回答2:

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!