Swift3:添加带代码的按钮

时间:2016-07-16 22:20:22

标签: ios swift2 swift3

我正在阅读苹果swift(iOS)文档,但它是为Swift 2编写的,我使用的是Swift 3.我想以编程方式添加一个按钮,但它似乎有一个变化,我找不到如何解决它。

以下是Swift 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")
}
}

我在'fix-it'之后做出的唯一改变是在选择器中显示错误:

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

这应该打印“按下按钮”,但它没有。有什么帮助吗?

3 个答案:

答案 0 :(得分:20)

我的代码:

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

答案 1 :(得分:13)

尝试这样的事情。我没有经过测试,但应该可以运作:

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

答案 2 :(得分:2)

找到解决方案。出于某种原因:

func ratingButtonTapped(button: UIButton)

按钮前需要“_”。所以它应该是:

func ratingButtonTapped(_ button: UIButton)

代码的另一部分必须是:

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

感谢您的帮助:)您的方法也可能是正确的,但这就是Apple想要的。