【问题标题】:Connecting multiple outlets to single action?将多个插座连接到单个操作?
【发布时间】:2015-10-29 20:46:11
【问题描述】:

我正在 XCode Beta 7 (Swift2) 中创建键盘扩展。

我正在尝试将多个按钮连接到单个操作。

但是,当我将所有按钮插座连接到此操作时,它会导致我的键盘崩溃,这让我觉得我缺少一些东西。

@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()

}

【问题讨论】:

    标签: xcode swift uibutton iboutlet custom-keyboard


    【解决方案1】:

    将同一个动作附加到多个按钮上不是问题,是一种常用技术。

    但是,您将 Label 设置为强制展开,如果它为 nil,则会崩溃。

    我的猜测是您的 Label 插座未连接,因此 Label 在运行时为零。

    将 Label 的类型从 UIButton! 更改为 UIButton?,然后将代码更改为使用“if let”可选绑定,以便仅在 label 非 nil 时使用 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()
    
    }
    

    【讨论】:

    • 谢谢!您能否给我更多关于“将代码更改为使用“if let”可选绑定以仅在 label 不为 nil 时使用 Label 执行代码的信息。”好像?就像我说的,我在这方面是个菜鸟,还在学习基础知识。 :) 再次感谢您!!!
    • 我刚刚编辑了我的帖子以提供示例代码。我可怜你,因为你是新人。通常我们对“给我看代码”类型的问题不屑一顾,并要求你先做自己的研究。
    • 谢谢您——请原谅我,我会记住这一点,以备将来使用。但是,在实现代码并连接插座后,每当我点击一个按钮时,键盘仍然会崩溃。
    • 所以发布你的崩溃细节。哪条线路崩溃了。您收到的确切错误消息是什么?
    • 我没有收到任何错误代码,但是当我在我的 IOS 设备上构建应用程序并进行模拟时,每当我点击与“ButtonTapped”关联的按钮时,键盘就会崩溃。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-04
    • 1970-01-01
    • 1970-01-01
    • 2012-04-03
    相关资源
    最近更新 更多