设置按钮类型

时间:2015-01-09 09:14:34

标签: ios swift uibutton xcode6

我正在以编程方式创建一个按钮,我想知道如何设置该按钮的UIButtonType。

这就是我创建按钮的方式:

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

没有“setButtonTypeFor ...”方法,比如你如何更改标题的文字,显然这不起作用:

headerPlusButon.buttonType = UIButtonType.ContactAdd

2 个答案:

答案 0 :(得分:10)

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

来自swift 2UIButton声明替换为以下行。

let button = UIButton(type: .System) as UIButton

答案 1 :(得分:1)

这是我的代码

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)

我希望它可以帮到你!