Swift3:添加带代码的按钮

pRi*_*BuG 9 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")
}
}
Run Code Online (Sandbox Code Playgroud)

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

button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(button:)), for: .touchDown)
Run Code Online (Sandbox Code Playgroud)

这应该打印"按下按钮",但它没有.有帮助吗?

小智 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 ")
}
Run Code Online (Sandbox Code Playgroud)


axe*_*xel 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")
}
Run Code Online (Sandbox Code Playgroud)