在Apple教程中,Type没有成员



我刚开始学习Swift。我正在遵循这个苹果教程,但我遇到了这个错误。我从教程中复制了确切的代码。不确定我哪里错了。

错误消息:

"类型'RatingControl'没有成员'ratingButtonTapped(按钮:('">

//Mark: Private Methods
private func setupButtons() {
for _ in 0..<5 {
//Create the button
let button = UIButton()
button.backgroundColor = UIColor.red
//Add constraints
button.translatesAutoresizingMaskIntoConstraints = false
button.heightAnchor.constraint(equalToConstant: 44.0).isActive = true
button.widthAnchor.constraint(equalToConstant: 44.0).isActive = true
//Setup the button action
button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(button:)), for: .touchUpInside)
//Add the button to the stack
addArrangedSubview(button)
//Add the new button to the rating button array
ratingButtons.append(button)
}
}

要获得按钮操作的初始值,RatingControl.swift类将类似

import UIKit
@IBDesignable class RatingControl: UIStackView {
//MARK: Initialization
override init(frame: CGRect) {
super.init(frame: frame)
}
required init(coder: NSCoder) {
super.init(coder: coder)
}
//MARK: Button Action
@objc func ratingButtonTapped(button: UIButton) {
print("Button pressed")
}
}

使用代码创建一个名为RatingControl.swift的文件并运行您的项目。这个问题将得到解决。

如果您已经有了完整的类,那么只需在方法ratingButtonTapped之前添加@objc

更多信息:您可以下载当前教程的完整项目。下载链接位于底部。

我们确实需要查看整个RatingControl类,以便给您一个完整的答案。然而,基于错误的问题是,在RatingControl类中没有名称为ratingButtonTapped的函数。应该有一个像下面这样的类,以便将其注册为按钮的目标。

.addTarget用法示例:

class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//Setup the button action
let button = UIButton()
button.addTarget(self, action: #selector(ratingButtonTapped(_:)), for: .touchUpInside)
view.addSubview(button)
}

@objc func ratingButtonTapped(sender: UIButton) {
// Triggered when the button is pressed
}
}

最新更新