感謝大家的評論和回覆。我原本希望有一種方法來改變變量類型,但現在意識到這是絕對不鼓勵的,並且違背了Swift自己的類型安全特性。
想要更改變量類型的原因是因爲我想在所有項目符號對象的屬性上創建自動佈局約束。我知道這是因爲UIImageView
和UILabel
都是從UIView
繼承的,根據情況初步確定和設置一個變量會容易得多,這樣我就只需要擔心創建一個集合NSLayoutConstraint
's,使用那一個變量。
無論如何,我回答了我自己的問題,並決定最好的解決方案是創建一個額外的UIView
對象作爲每個案件的容器。我仍然只使用一個變量和一組NSLayoutConstraint
來設置容器是否應該容納UIImageView
或UILabel
。此外,通過這樣做,今後我可以使用單個容器對象來獲得所需的附加約束。
這裏是什麼樣子:
class bullet {
var bulletStyleContainer: UIView
init(bulletStyle: AnyObject) {
bulletStyleContainer = UIView()
createBulletStyle(bulletStyle)
}
func createBulletStyle(style: AnyObject) {
if style is UIImageView {
bulletStyleContainer.addSubview(style as! UIImageView)
} else if style is UILabel {
bulletStyleContainer.addSubview(style as! UILabel)
} else {
let style = style as! UIView
style.backgroundColor = UIColor.blackColor()
bulletStyleContainer.addSubview(style)
}
let leftPinConstraint = NSLayoutConstraint(item: style, attribute: .Leading, relatedBy: .Equal, toItem: bulletStyleContainer, attribute: .Leading, multiplier: 1.0, constant: 0)
let rightPinConstraint = NSLayoutConstraint(item: bulletStyleContainer, attribute: .Trailing, relatedBy: .Equal, toItem: style, attribute: .Trailing, multiplier: 1.0, constant: 0)
let topPinConstraint = NSLayoutConstraint(item: style, attribute: .Top, relatedBy: .Equal, toItem: bulletStyleContainer, attribute: .Top, multiplier: 1.0, constant: 0)
let bottomPinConstraint = NSLayoutConstraint(item: bulletStyleContainer, attribute: .Bottom, relatedBy: .Equal, toItem: style, attribute: .Bottom, multiplier: 1.0, constant: 0)
style.setTranslatesAutoresizingMaskIntoConstraints(false)
NSLayoutConstraint.activateConstraints([leftPinConstraint,rightPinConstraint,topPinConstraint,bottomPinConstraint])
}
初始化後,'bulletStyle'確實有UILabel'或'UIImageView'的'的潛在價值,但它的類型是'AnyObject',其中,按照Swift的類型安全功能在聲明變量後不能更改。 – aaplmath
您可以嘗試將對象封裝到自定義類中,而不是使用AnyObject。然後你可以添加邏輯來處理你的用例。 –
@aaplmath正確...但如果我初始化一個新的子彈實例,說:'var newBullet = bullet()',然後我嘗試更改bulletStyle的文本,因爲它初始化爲默認的'UILabel',如: 'newBullet.bulletStyle.text'它不能識別'bulletStyle'具有'.text'屬性並引發錯誤。 – Yonny