[英]How to replace a custom subview dynamically in a custom view class?
給定RoundedIcon: UIView
類型的兩個視圖RoundedIcon: UIView
:
class ContactRoundedIcon: RoundedIcon
class PhoneRoundedIcon: RoundedIcon
和UIView
類型的ContactItem
類
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
的部分將可見。 我猜你也不想。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.