【问题标题】:Disable button in another view在另一个视图中禁用按钮
【发布时间】:2016-05-05 16:21:35
【问题描述】:

是否可以禁用另一个视图中的按钮?

如果我尝试这样做:

refreshbutton.enabled = false

我在两个 .swift 文件中都有这个:

@IBOutlet var refreshbutton: UIBarButtonItem!

程序停止,我收到一个致命错误。

编辑:

我尝试了以下操作:

 let otherviewcontroller: SerialViewController = SerialViewController (nibName: nil, bundle: nil)
 let button1 = otherviewcontroller.refreshbutton
 let loading1 = otherviewcontroller.loading
 loading1.showLoading2()
 button1.enabled = false

为什么我可以访问另一个控制器中的 showLoading2() 函数,但为什么我不能访问按钮?它抛出一个致命异常并说“button1”为 nil,但为什么呢?

【问题讨论】:

  • 将代码发布到程序以及您收到的具体错误可能会有所帮助。
  • 您应该使名称独一无二。虽然这不是必需的,但它有助于确保您在正确的按钮上调用正确的属性。

标签: ios swift button


【解决方案1】:

您可以通过发送通知并在要禁用它的类中观察它来简单地做到这一点

可以在您想要禁用按钮的视图中使用以下代码发送通知

NSNotificationCenter.defaultCenter().postNotificationName("kDiableRefreshButton", object: nil)

在您想要禁用按钮的课堂上接收通知

NSNotificationCenter.defaultCenter().addObserver(self, selector: "diableRefreshButtonNotification:", name:"kDiableRefreshButton", object: nil)

实现代表通知调用的方法

func diableRefreshButtonNotification(notification: NSNotification){
//Disable your button or Do whatever stuff you want
}

当您的视图正在处理时,不要忘记删除通知

NSNotificationCenter.defaultCenter().removeObserver(self, name: "kDiableRefreshButton", object: nil)

【讨论】:

    【解决方案2】:

    您可以像这样从UIViewController 内部禁用左侧导航按钮,而无需使用任何IBOutlet

    self.navigationItem.leftBarButtonItem.enabled = NO
    

    禁用右侧导航按钮:

    self.navigationItem.rightBarButtonItem.enabled = NO
    

    【讨论】:

      【解决方案3】:

      这显然是可能的。您只需先引用该 viewController,然后访问该 SerialViewController 的“刷新按钮”

      示例 -

      let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
      if let otherviewcontroller = appDelegate.window?.rootViewController as? SerialViewController {
          let button1 = otherviewcontroller.refreshbutton
          let loading1 = otherviewcontroller.loading
          loading1.showLoading2()
          button1.enabled = false
      }
      

      【讨论】:

      • 我试过这个,但它没有被执行,因为 viewController 是 nil !?你有什么想法吗?
      • 你能把代码分享给我吗,我能提供更好的帮助。
      • 我用我正在使用的代码编辑了我的第一篇文章。谢谢你的帮助
      • 好像返回nil,所以if里面什么都没执行,但是不知道为什么?!
      猜你喜欢
      • 2012-10-23
      • 1970-01-01
      • 1970-01-01
      • 2021-10-08
      • 2016-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多