Ios Swift3:添加带有代码的按钮
我正在阅读苹果的swift(iOS)文档,但它是为swift 2编写的,我使用的是swift 3。我想以编程方式添加一个按钮,但它似乎有变化,我找不到如何修复它 以下是Swift 2示例的代码:Ios Swift3:添加带有代码的按钮,ios,swift2,swift3,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) //
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")
}
}
在“修复它”显示错误后,我所做的唯一更改是选择器中的以下内容:
button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(button:)), for: .touchDown)
这应该打印“按钮按下”,但它没有。有什么帮助吗?试试这样的方法。我还没有测试,但它应该可以工作:
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")
}
找到了解决办法。出于某种原因:
func ratingButtonTapped(button: UIButton)
需要在按钮前加一个“u”。因此,它应该是:
func ratingButtonTapped(_ button: UIButton)
代码的另一部分必须是:
button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(_:)), for: .touchDown)
感谢您的帮助:)您的方法可能也是正确的,但这正是苹果想要的。我的代码:
button.backgroundColor=UIColor.red
button.addTarget(自身,操作:#选择器(RatingControl.ratingButtonTapped(:)),用于:。着陆)
重写变量intrinsicContentSize:CGSize{
//重写func intrinsicContentSize()->CGSize{
//...
返回CGSize(宽:240,高:44)
}
//标记:按钮动作
功能分级按钮已标记(u按钮:ui按钮){
打印(“按了按钮,您的分级控件如何。分级按钮已按(按钮:)方法?这取决于它的实现。我不知道这是否是一个问题,因为我写的所有东西都来自苹果的例子…这里是链接:tinyurl.com/q5oouqz@OnurTuna选择器仅引用它,它不应依赖于implementation@Gerald我的意思是,如果有一个错误取决于参数,例如,在swift 3中,所有参数与swift 2不同,ETER甚至是第一个参数都被命名。更好的解决方案是#选择器(RatingControl.ratingButtonTapped(button:)
。这样,您就不必为了在Selector中使用而更改功能,这对我帮助很大。谢谢,这是使用Swift 3而不是Swift 2时文档中问题的正确答案。