【问题标题】:difficulties to find and modify a subview查找和修改子视图的困难
【发布时间】:2016-03-27 16:07:46
【问题描述】:

我在获取对子视图的引用时遇到了一些困难。 基本上我有一个包含自定义 UIView 集合的 UIView。 我需要的是获取一个特定视图的引用来修改它。

我尝试了 2 种不同的方法,其中第一种作为概念是这样的:

for i in 1...8 {
    let myCustomView = MyCustomView(frame: CGRect(0, 0, 100, 100)) // frame is with fake numbers just to write the snippet
    myCustomView.customProperty = some property
    myCustomView.image = some UIImage
    myCustomView.tag = i

    addSubview(myCustomView)
}

我试图以这种方式获得对假设带有标签 2 的视图的引用:

if let viewWithTag = self.viewWithTag(2) as! MyCustomView {
    viewWithTag.image = a different Image
}

我可以看到 viewWithTag 不是 nil,但是对于我更改的任何属性,应用程序中都没有反映任何内容。

访问子视图的另一种方法是:

let myViews = self.subviews.filter({$0 is MyCustomView})
let specificView = myViews[1] as! MyCustomView

specificView.image = something else

在这种情况下,我的 myViews 包含所有子视图,specificView 包含特定视图,但应用程序中也没有任何反映

请注意,MyCustomView 是 UIImageView 类型,主容器是 UIView

我的方法正确吗?

提前致谢

【问题讨论】:

    标签: swift uiview uiimageview subviews


    【解决方案1】:

    您可能需要轻推图像视图以使其意识到它需要更新。

    设置好图片后,尝试做一个:

    viewWithTag.setNeedsDisplay()
    

    另外,考虑使用标签以外的东西来区分您的自定义图像视图(例如名称的字符串属性怎么样?),因为标签中使用的通用整数并不能真正告诉您它们的用途。

    【讨论】:

      猜你喜欢
      • 2016-09-10
      • 1970-01-01
      • 2020-07-27
      • 1970-01-01
      • 2012-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-30
      相关资源
      最近更新 更多