感谢大家的评论和回复。我原本希望有一种方法来改变变量类型,但现在意识到这是绝对不鼓励的,并且违背了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