2015-09-04 53 views
0

这是一个重复的问题。我已经通过复制和粘贴到x代码尝试了几个答案。然而我的按钮操作从未被调用。迅速制作一个按钮

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

任何想法,为什么这是行不通的?

+0

这是奇怪的,它看起来正确的给我。你能够点击UI中的按钮吗? – AdamPro13

+0

看来我不能。我为UIControlState.Highlighted添加了一个不同的标题,标题不变。还有其他方法我应该检查吗? – LeoReubelt

+0

此外,我在xib中制作的按钮在拖动创建IBAction后也不起作用。 – LeoReubelt

回答

0

buttonAction这里没有绑定到任何UI元素。您需要添加@IBAction,像这样:

@IBAction func buttonAction(sender:UIButton!) 

之后,按(并按住)Ctrl键在键盘上,然后单击并从你的按钮拖动(你应该看到一个蓝色的线从它拉伸)直到您到达buttonAction(sender:UIButton!)文本。你应该看到一个蓝色的矩形出现在文字周围。释放鼠标和键。如果您在排水沟中看到黑点(行号旁边的竖条),您就完成了!

+0

OP没有使用Interface Builder。 – Arbitur

0

相反的:

let button = UIButton.buttonWithType(UIButtonType.System) as UIButton 

用途:

let button = UIButton(type: .System) 

随着这种变化,你的代码工作完美。

-1
let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 100))