Xcode 7 beta 5,Swift 2:UITableViewCell的子视图在运行时未添加到contentView [英] Xcode 7 beta 5, Swift 2: UITableViewCell's subviews are not added to the contentView at runtime
问题描述
使用Xcode 7 beta 5和Swift 2时出现以下现象:
使用在故事板中创建的自定义UICollectionViewCell时,单元格的子视图不会添加到单元格的 contentView
。因此,单元格在运行时保持空白。
但是,如果我为单元格创建自定义单元格类,然后以编程方式将子视图添加到contentView并设置其 frame
显示单元格的内容:
class Cell:UITableViewCell {
@IBOutlet弱var标签:UILabel!
覆盖func awakeFromNib(){
super.awakeFromNib()
NSLog(subiews.count =%d,contentView.subviews.count)//打印0
contentView.subviews.count
contentView.addSubview(label)
label.frame = CGRect(x:0,y:0,width :200,身高:21)
}
}
再次,无需手动添加标签(已在故事板中添加!)并设置其框架,它在运行时将不可见!在故事板中,标签是内容视图的子视图。在运行时它不是。
我在最新的Xcode 6中使用Swift 1.2无法观察到这种行为。
有人可以证实这种愚蠢的行为吗?并且可能提供更简单的解决方法?
编辑:
在添加这些视图后,可以应用对单元格子视图的幸运视图约束以编程方式 contentView
。因此,至少手动设置它们的帧是不必要的。
这里有一个类似的问题
Following phenomena happens when using Xcode 7 beta 5 and Swift 2:
When using a custom UICollectionViewCell that is created in the storyboard, the cell's subviews are not added to the cell's contentView
. Thus the cell remains blank on runtime.
If I however create a custom cell class for the cell and then programmatically add the subviews to the contentView and set their frame
the cell's content is displayed:
class Cell : UITableViewCell {
@IBOutlet weak var label: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
NSLog("subiews.count=%d", contentView.subviews.count) // prints "0"
contentView.subviews.count
contentView.addSubview(label)
label.frame = CGRect(x: 0, y: 0, width: 200, height: 21)
}
}
Again, without manually adding the label (that has been added in the storyboard!) and setting its frame, it would not be visible at runtime! In the storyboard the label is a subview of the content view. At run time it is not.
I cannot observe this behavior in latest Xcode 6 with Swift 1.2.
Can somebody confirm this silly behavior? And maybe provide an easier workaround?
Edit:
Luckily view constraints on the cell's subviews are applied after these views have been added programmatically to contentView
. Thus at least manually setting their frames is not necessary.
There is a similar question here UITableView Empty with iOS 9 beta 5 update
And my answer for it https://stackoverflow.com/a/32052154/2674336
I can't say if this is a universal solution, but in the exact same scenario (tablviewcell content empty at runtime after updating to XCode 7 beta 5) this solved it for me:
I had to go through every single item inside the content view (including all constraints) and tick the checkbox "Installed" in the properties inspector. Initially only wR hR was checked.
这篇关于Xcode 7 beta 5,Swift 2:UITableViewCell的子视图在运行时未添加到contentView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!