【问题标题】:Looping through UIImageViews in UIView - Swift在 UIView 中循环 UIImageViews - Swift
【发布时间】:2015-10-10 13:44:00
【问题描述】:

我一直在尝试在 Swift 中做一些与下面的代码示例(目标 C)非常相似的事情。有没有人能够提供如下所示功能的 Swift 实现或类似的东西?

- (UIImageView *) getSectorByValue:(int)value {
UIImageView *res;
NSArray *views = [container subviews];
for (UIImageView *im in views) {
    if (im.tag == value)
        res = im;
}
return res;

}

【问题讨论】:

    标签: ios swift uiview uiimageview swift2


    【解决方案1】:

    这是 Swift 中类似的实现:

    func getSectorByValue(value: Int) -> UIImageView? {
        for subView in container.subviews {
            if subView.tag == value {
                return subView as? UIImageView
            }
        }
        return nil
    }
    

    【讨论】:

      【解决方案2】:

      这样的事情应该可以工作。

      func getSectorByValue(value: Int) -> UIImageView? {
          let views = container.subviews() 
          if let i = views.indexOf({$0.tag == value}) {
              return views[i] as? UIImageView
          }
          return nil
      }
      

      【讨论】:

      • 将 UIView 作为 UIImageView 返回是不高兴的。
      【解决方案3】:

      手动循环子视图是不必要的复杂。

      有一个 UIView 方法 viewWithTag 用 1 行代码获取所需的视图:

      func getSectorByValue(value: Int) -> UIImageView? 
      {
          return container.viewWithTag(value) as? UIImageView
      }
      

      【讨论】:

      • 为什么投反对票?与 OP 使用的方法相比,这是对实际问题的更清洁、更有效的解决方案。
      • 我觉得根据这个答案,其他答案应该被否决。
      • 问题是XY problem的示例
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-15
      • 2023-03-13
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多