给定两种类型的视图RoundedIcon: UIView
:
class ContactRoundedIcon: RoundedIcon
class PhoneRoundedIcon: RoundedIcon
和一ContactItem
类类型UIView
class ContactItem: UIView {
var icon: RoundedIcon = PhoneRoundedIcon()
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
translatesAutoresizingMaskIntoConstraints = false
addSubview(icon)
}
/* ... */
NSLayoutConstraint.activate([
icon.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 0),
icon.topAnchor.constraint(equalTo: topAnchor, constant: 0)
)]
}
和一个班级 class ContactDropDownList: UIControl
当我分配ContactRoundedIcon
给contactItem.icon
财产时。
class ContactDropDownList: UIControl {
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
let contactItem = ContactItem()
contactItem.icon = ContactRoundedIcon()
self.addSubview(contactItem)
}
然后图标不会从PhoneRoundedIcon
变为ContactRoundedIcon
。至少我没有在模拟器中看到它。
该ContactDropDownList
视图被添加为故事板中的子视图。其余的视图以编程方式编写。当他们自己时,他们没事。ContactItem
实例中的图标分配不起作用。
怎么了?如何更改图标?
试试这个:
class ContactItem: UIView {
var icon: RoundedIcon = PhoneRoundedIcon() {
didSet {
// get rid of the old icon
oldValue.removeFromSuperview()
// add a new one
addSubview(icon)
// setup layout (I'm not sure if you use autolayout or set frames, but I don't see any layout setup, which might also be a problem)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
translatesAutoresizingMaskIntoConstraints = false
addSubview(icon)
}
...
}
在didSet
你需要摆脱旧的图标,并添加一个新的视图。否则,您看到旧图标是正常的(`commonInit' 在初始化程序中被调用,当您设置新图标时,它已全部设置完毕,不会再次被调用)。
此外,您还没有显示任何布局代码,因此请确保正确设置框架,如果使用自动布局,请确保设置约束。
编辑
旧视图本身不必删除。但是您应该删除它,除非您确实有充分的理由将其保留在那里。首先,您希望释放未使用的对象。通过将其保留在视图中,您将保留它。其次,如果新的icon
有一些透明的部分(或比旧的小),旧的部分icon
将是可见的。我想你也不想要。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句