我正在 XCode Beta 7 (Swift2) 中创建键盘扩展。
我正在尝试将多个按钮连接到一个操作。
但是,当我将所有按钮 socket 连接到此操作时,它会导致我的键盘崩溃,这让我觉得我缺少了一些东西。
@IBOutlet weak var Label: UIButton!
@IBAction func ButtonTapped(sender: AnyObject) {
Label.setTitle("Hello!", forState: .Normal)
Label.hidden = false
Label.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.5)
NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "hideLabel", userInfo: nil, repeats: false)
}
@objc func hideLabel() {
Label.hidden = true
Label.backgroundColor = UIColor.clearColor()
}
最佳答案
将相同的操作附加到多个按钮不是问题,并且是一种常见技术。
但是,您将 Label 设置为强制展开,如果为零,则会崩溃。
我的猜测是您的 Label 导出未连接,因此 Label 在运行时为零。
将 Label 的类型从 UIButton!
更改为 UIButton?
,然后将代码更改为使用“if let”可选绑定(bind),以便仅使用 Label if label 执行代码非零。
顺便说一句,Swift 有很强的命名约定。变量名称应以小写字母开头,变量名称的其余部分使用“驼峰式大小写”。只有类名和类型名应以大写字母开头。所以“标签”应该改为“标签”。养成遵循这种风格的习惯。它可以为您和其他阅读代码的人提供清晰的视觉提示,让您了解名称所指的事物类型。
最后,“标签”对于按钮来说是一个可怕的名字。它是一个按钮,而不是 UILabel。称其为“myButton”或其他名称。
编辑
代码可能如下所示:
@IBOutlet weak var myButton: UIButton?
@IBAction func ButtonTapped(sender: AnyObject)
{
println("myButton = \(myButton)") //See if myButton is nil
if let myButton = myButton
{
myButton.setTitle("Hello!", forState: .Normal)
myButton.hidden = false
myButton.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.5)
NSTimer.scheduledTimerWithTimeInterval(2, target: self,
selector: "hidemyButton",
userInfo: nil, repeats: false)
}
}
@objc func hidemyButton()
{
myButton.hidden = true
myButton.backgroundColor = UIColor.clearColor()
}
关于xcode - 将多个 socket 连接到单一操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31860228/