【问题标题】:Check UIButton already exists or not in Swift检查 UIButton 在 Swift 中是否已经存在
【发布时间】:2014-07-03 10:10:38
【问题描述】:

我为这个主题找到了 Objective-C 编码。但问题是 Objective-C 中的大多数类和函数在 swift 编程语言中已被弃用。

我在带有flagForAction[Boolean Value] 的 UITableView 中使用 UIButton。所以我想要实现的是,如果 UIButton 被创建一次,就不需要重新创建它。所以为此我需要检查 UIButton 是否已经存在。有人为此建议我使用标签的概念,将特定标签应用于此 UIButton 并检查视图上是否存在。但我不知道该怎么做。

【问题讨论】:

  • Objective-C 已弃用?我没有收到那个消息。
  • @dasdom 像这样创建一个 UIButton,var MyButton:UIButton = UIButton(), MyButton.class ,在 Swift 中标有 .class 交叉标记。
  • 你拿错了。在 Swift 中,您可以使用 myButton is UIButton 检查课程。顺便说一句:实例不应以小写字母开头。我建议您在使用 Swift 编写应用程序之前阅读 Swift 书籍。
  • @dasdom 好的。那么这个问题的答案呢?
  • 按钮是否在表格视图单元格中?

标签: ios uibutton swift


【解决方案1】:

设置标签:

myButton.tag = 1234 // some unique value, probably better to define as an enum or constant

按标签检索视图(可能在cellForRowAtIndexPath):

if let myButton = tableviewCell.viewWithTag(1234) { // change tableviewCell for whatever your tableview cell variable name is
    // myButton already existed
} else {
    // TableviewCell doesn't contain a myButton, so create one here and set the tag as above
}

【讨论】:

    【解决方案2】:

    swift 2.0

    for view in myview.subviews {
    
          if let btn : UIButton = view as? UIButton {
               // access button here, either tag or title etc..
          }
    
     }
    

    【讨论】:

      【解决方案3】:

      我以视图为例。如果您不想使用按钮的标记属性,您还可以使用按钮的accessibilityIdentifier 属性来识别按钮。 例如:

          var button = UIButton(frame: CGRectMake(0, 0, 100, 44))
          button.accessibilityIdentifier = "button 1"
          self.view.addSubview(button)
      

      在这里,我创建了一个带有accessibilityIdentifier“button 1”的按钮

      在创建下一个按钮时,我将检查子视图是否包含带有accessibilityIdentifier“按钮1”的按钮,如下所示

          var subviews : NSArray = self.view.subviews
          for button : AnyObject in subviews{
      
              if(button .isKindOfClass(UIButton)){
      
                  if(button.accessibilityIdentifier == "button 1"){
      
                      println("Button Already Exists")
                  }else{
                      println("Create new button")
      
                  }
              }
          }
      

      【讨论】:

      • 奇怪的破解。可访问性标识符应该用于其他用途。
      • 遍历所有子视图的效率极低。对于使用辅助功能的用户来说,这将是糟糕的黑客行为。根据@dasdom 的回答阅读文档并使用标签或 UITableView 的子类
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-13
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      相关资源
      最近更新 更多