Swift 查找和修改子视图的困难
我很难获得对子视图的引用。 基本上,我有一个UIView,其中包含一组自定义UIView。 我需要的是获得一个特定视图的引用来修改它 我尝试了两种不同的方法,其中第一种方法是概念:Swift 查找和修改子视图的困难,swift,uiview,uiimageview,subviews,Swift,Uiview,Uiimageview,Subviews,我很难获得对子视图的引用。 基本上,我有一个UIView,其中包含一组自定义UIView。 我需要的是获得一个特定视图的引用来修改它 我尝试了两种不同的方法,其中第一种方法是概念: 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.cu
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)
}
let myViews = self.subviews.filter({$0 is MyCustomView})
let specificView = myViews[1] as! MyCustomView
specificView.image = something else
我试图通过以下方式获取对标签2的视图的引用:
if let viewWithTag = self.viewWithTag(2) as! MyCustomView {
viewWithTag.image = a different Image
}
我可以看到viewWithTag不是nil,但对于我更改的任何属性,应用程序中都没有反映任何内容
访问子视图的另一种方法如下:
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)
}
let myViews = self.subviews.filter({$0 is MyCustomView})
let specificView = myViews[1] as! MyCustomView
specificView.image = something else
在本例中,我有包含所有子视图的MyView,specificView包含特定视图,但应用程序中没有反映任何内容
请注意,MyCustomView是UIImageView类型,主容器是UIView
我的方法正确吗
提前感谢您可能需要轻推图像视图,使其意识到需要更新
设置图像后,请尝试执行以下操作:
viewWithTag.setNeedsDisplay()
也可以考虑使用标签以外的东西来区分你的自定义图像视图(比如名字的字符串属性),因为标签中使用的通用整数并不能真正告诉你它们在使用什么。p>