【问题标题】:Find out the parent view of a clicked button in swift快速找出单击按钮的父视图
【发布时间】:2020-12-05 05:57:39
【问题描述】:

我有一些代码,其中有 3 个按钮,我想在单击时找出这些按钮的父视图

 @IBAction func resizeButtonClicked(sender: UIButton) {
    if(sender.isEqual(resizeButton)) {
        //This is to convert to small square
    } else if(sender.isEqual(maximizeButton)) {
        //This is to convert to maximized view
    } else if(sender.isEqual(closeButton)) {
        //This is to close the view completely

    }
}

现在我可以识别发件人按钮,但如何识别此按钮所在的视图?

谢谢

尼基尔

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    请尝试以下方法

    sender.superview
    

    【讨论】:

      【解决方案2】:

      我不想创建自定义类,也不想使用accessibilityHin:

          func performAction(_ sender : AnyObject?)
      {
          let cell = sender?.superview??.superviewOfClassType(UITableViewCell.self) as! UITableViewCell
          let tbl = cell.superviewOfClassType(UITableView.self) as! UITableView
          let indexPath = tbl.indexPath(for: cell) 
          let myData = myDataArray[indexPath.row]
          ...
      }
      

      【讨论】:

        【解决方案3】:

        如果您正在视图层次结构中或什至在父控制器或任何其他响应者中寻找特定父级,您可以使用此扩展:

        extension UIResponder {
            func nextFirstResponder(where condition: (UIResponder) -> Bool ) -> UIResponder? {
                guard let next = next else { return nil }
                if condition(next) { return next }
                else { return next.nextFirstResponder(where: condition) }
            }
        }
        

        使用示例

        以下返回包含myButtontableViewController。无论在视图和子视图中嵌套多深。

        let tvc = myButton.nextFirstResponder { $0 is UITableViewController }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-06-14
          • 1970-01-01
          • 2016-12-06
          相关资源
          最近更新 更多