【问题标题】:Recursively find a view of a specific type iOS递归查找特定类型iOS的视图
【发布时间】:2019-07-13 20:01:09
【问题描述】:

我有一个UIView 我想解析视图的所有子视图并返回CustomClass 类型的子视图实例

使用view.subviews,我只能访问直接子视图,我想解析所有子视图并返回符合条件的子视图。

findView(key : uniqueKey , view : UIView)

for subview in view.subviews {
if subview.uniqueKey == key 
return subview       // and break 
else 
continue with recursively searching
}

我知道我需要递归解决这个问题,但我确信这个视图只有一个实例存在,所以一旦我找到我想要返回的实例并中断递归。

我怎样才能达到同样的效果。

【问题讨论】:

  • 视图包含它可能只有一个匹配子视图或者它可能是多个?
  • 不,因为键是唯一的,它只会匹配一个子视图

标签: ios swift recursion uiview subview


【解决方案1】:
func findView(key: String, view: UIView) -> UIView? {
    for subview in view.subviews {
        if subview.key == key {
            return subview
        } else {
            return findView(key: key, view: subview)
        }
    }

    return nil
}

注意:键未在 UIView 上定义,因此定位逻辑假设您已通过协议或扩展定义了它

【讨论】:

    【解决方案2】:

    这里是带有视图标签的功能,你可以用你的唯一键替换它。

    func findView(tag :Int, view : UIView) -> UIView? {
        if view.tag == tag {
            return view
        }
    
        for subview in view.subviews {
            if let v = findView(tag: tag, view: subview) {
                return v
            }
        }
    
        return nil
    }
    

    【讨论】:

      【解决方案3】:

      您想使用 uniqueKey 为您的自定义视图提供资金,然后使用以下函数来获得您要求的结果。

      func findView(key : uniqueKey , view : UIView) -> customView? {
              var fondSubview:customView!
      
              for subview in view.subviews {
                  if subview.uniqueKey == key {
                     fondSubview = subview as! customView
                      break
                  }
              }        
              return fondSubview
          }
      

      【讨论】:

        【解决方案4】:

        您可以使用这个通用的 UIView 扩展方法来查找特定类的任何对象。如果该类不存在子视图,则返回 nil。

        extension UIView {
            func find<T:UIView>(_ ofType:T.Type) -> T? {
                if let test = subviews.first(where: { $0 is T }) as? T {
                    return test
                } else {
                    for view in subviews {
                        return view.find(ofType)
                    }
                }
                return nil
            }
        }
        

        用法

        let firstBtn = self.view.find(UIButton.self)
        

        【讨论】:

          猜你喜欢
          • 2014-04-09
          • 2019-03-22
          • 1970-01-01
          • 1970-01-01
          • 2019-01-12
          • 2012-09-21
          • 2017-07-07
          • 2015-11-24
          • 2022-12-06
          相关资源
          最近更新 更多