2016-07-16 68 views
8

我正在閱讀蘋果swift(iOS)文檔,但其編寫的Swift 2和我使用Swift 3.我想以編程方式添加按鈕,但它似乎有一個變化,我無法找到如何要解決這個問題。Swift3:添加代碼按鈕

這裏是代碼爲夫特2例如:

import UIKit 

class RatingControl: UIView { 

// MARK: Initialization 

required init?(coder aDecoder: NSCoder) { 
    super.init(coder: aDecoder) 

    // Buttons 
    let button = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44)) 
    button.backgroundColor = UIColor.red() 
    button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(_:)), forControlEvents: .TouchDown) 
    addSubview(button) 
} 

override func intrinsicContentSize() -> CGSize { 
    return CGSize(width: 240, height: 44) 
} 

// MARK: Button Action 

func ratingButtonTapped(button: UIButton){ 
    print("Button pressed") 
} 
} 

i之後所做的唯一變化的'固定-它顯示出錯誤是這樣的選擇:

button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(button:)), for: .touchDown) 

這應該打印了「按下按鈕」,但不是。任何幫助?

+0

那你RatingControl.ratingButtonTapped(按鈕:)方法?這取決於它的實施。 –

+0

我不知道這是一個問題,因爲我寫的所有東西都是從蘋果的例子...這裏是鏈接:tinyurl.com/q5oouqz –

+0

@OnurTuna選擇器只引用它,它不應該依賴於執行 – Gerald

回答

12

嘗試類似這樣的事情。我沒有測試,但它應該工作:

let button = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44)) 
button.backgroundColor = UIColor.red 
button.addTarget(self, action: #selector(ratingButtonTapped), for: .touchUpInside) 
addSubview(button) 

func ratingButtonTapped() { 
    print("Button pressed") 
} 
+0

謝謝,幫了我很多。 –

2

找到解決方案。出於某種原因:

func ratingButtonTapped(button: UIButton) 

需要一個「_」按鈕之前。因此,它應該是:

func ratingButtonTapped(_ button: UIButton) 

和代碼的其他部分必須是:

button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(_:)), for: .touchDown) 

感謝您的幫助:)你的方法可能也是正確的,但多數民衆贊成在一個蘋果希望它。

+1

在swift 3中,與swift 2不同,所有參數都被命名,即使是第一個參數。一個更好的解決方案是'#selector(RatingControl.ratingButtonTapped(button :))'。這樣,你不必改變你的功能只是在選擇器中使用它 – Gerald

17

我的代碼:

button.backgroundColor = UIColor.red 

button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(_:)), for: .touchDown) 

override var intrinsicContentSize : CGSize { 
//override func intrinsicContentSize() -> CGSize { 
    //... 
    return CGSize(width: 240, height: 44) 
} 

// MARK: Button Action 
func ratingButtonTapped(_ button: UIButton) { 
    print("Button pressed ") 
} 
+0

謝謝,這是在使用Swift 3而不是2時文檔中問題的正確答案。 – meburbo