我创建了一个包含2个图片视图的自定义视图,我希望能够从一个到另一个设置动画,这是我的代码:
class FlashCard: UIView {
required init?(coder: NSCoder) {
super.init(coder: coder)
let firstImageView = UIImageView(frame: self.frame)
firstImageView.image = UIImage(named: "Lightning")
addSubview(firstImageView)
let secondImageView = UIImageView(frame: frame)
secondImageView.image = UIImage(named: "Tifa")
addSubview(secondImageView)
secondImageView.isHidden = true
}
func showBack() {
UIView.transition(from: firstImageView, to: secondImageView, duration: 1.0, options: UIViewAnimationOptions.transitionCrossDissolve, completion: nil)
}
}
但是在我的showBack
函数中,我收到了错误:使用未解析的标识符。
如何正确访问firstImageView
和secondImageView
?
答案 0 :(得分:2)
您必须使用两个属性:
var firstImageView: UIImageView!
var secondImageView: UIImageView!
目前你在init的本地范围内有两个UIImageView
,所以你不能在另一个类方法中使用它,而只是在init范围内。
所以:
class FlashCard: UIView {
var firstImageView: UIImageView!
var secondImageView: UIImageView!
required init?(coder: NSCoder) {
super.init(coder: coder)
firstImageView = UIImageView(frame: self.frame)
firstImageView.image = UIImage(named: "Lightning")
addSubview(firstImageView)
secondImageView = UIImageView(frame: frame)
secondImageView.image = UIImage(named: "Tifa")
addSubview(secondImageView)
secondImageView.isHidden = true
}
func showBack() {
UIView.transition(from: firstImageView, to: secondImageView, duration: 1.0, options: UIViewAnimationOptions.transitionCrossDissolve, completion: nil)
}
}
答案 1 :(得分:2)
图像视图不需要是任何变量的变量。
class FlashCard: UIView {
let firstImageView = UIImageView()
let secondImageView: UIImageView()
required init?(coder: NSCoder) {
super.init(coder: coder)
firstImageView.frame = frame
firstImageView.image = UIImage(named: "Lightning")
addSubview(firstImageView)
secondImageView.frame = frame
secondImageView.image = UIImage(named: "Tifa")
addSubview(secondImageView)
secondImageView.isHidden = true
}
func showBack() {
UIView.transition(from: firstImageView, to: secondImageView, duration: 1.0, options: UIViewAnimationOptions.transitionCrossDissolve, completion: nil)
}
}
必须在调用超级初始化器之前初始化类的属性,这就是为什么另一个答案使用隐式解包的可选变量。