我经历了Apple's iOS development with Swift tutorial并且已经陷入了第五阶段:
import UIKit
class RatingControl: UIStackView {
// MARK: Initialisation
override init(frame: CGRect) {
super.init(frame: frame)
setupButtons()
}
required init(coder: NSCoder) {
super.init(coder: coder)
setupButtons()
}
// MARK: Button action
@objc func ratingButtonTapped(button: UIButton) {
NSLog("Button pressed")
}
// MARK: Private methods
private func setupButtons() {
NSLog("setupButtons() called")
// 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)
}
}
setupButtons
被调用,我在Xcode的调试控制台中看到了该消息,该按钮在模拟器上显示为红色框:
然而,当我点击按钮时,没有任何反应 - 没有消息打印到调试控制台。
老实说,我不知道我是怎么开始调试的,因为所有编译/运行都没有错误,而且我已经尝试过将调试信息放在看似问题的地方。
有没有人对正在发生的事情有任何想法?
答案 0 :(得分:1)
我在Playgrounds中测试了您的代码,它按预期工作。因此,我希望您错误地使用RatingControl
。一个可能的错误可能是其超级视图之一isUserInteractionEnabled
设置为false
。检查此示例:
// A UIKit based Playground for presenting user interface
import PlaygroundSupport
import UIKit
class RatingControl: UIStackView {
// MARK: Initialisation
override init(frame: CGRect) {
super.init(frame: frame)
setupButtons()
}
required init(coder: NSCoder) {
super.init(coder: coder)
setupButtons()
}
// MARK: Button action
@objc func ratingButtonTapped(button: UIButton) {
print("Button pressed")
}
// MARK: Private methods
private func setupButtons() {
print("setupButtons() called")
// 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)
}
}
class A: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(RatingControl(frame: CGRect(x: 0, y: 0, width: 40, height: 40)))
// if you uncomment the following line, the button will stop working
// self.view.isUserInteractionEnabled = false
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = A()
如果不是这种情况,请包含您使用RatingControl
的代码,因为这就是错误的所在。
答案 1 :(得分:0)
它和我一起正常工作,我已经self.view.addSubview(button)
而不是addArrangedSubview(button)
。