2015-09-04 42 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))