在下面的程序中,无论我在 CGAffineTransform(scaleX:y:) 的参数中输入什么值,我都会得到相同的绘图结果。
这是为什么?
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = .gray
}
override func viewWillAppear(_ animated: Bool) {
let scalingView = ScalingView(frame: self.view.bounds)
self.view.addSubview(scalingView)
}
}
import UIKit
class ScalingView: UIView {
let subview: UIView!
override init(frame: CGRect) {
subview = UIView()
super.init(frame: frame)
addSubview(subview)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
subview.backgroundColor = .white
let subviewSize = 100
subview.frame.size = CGSize(width: subviewSize, height: subviewSize)
subview.center = CGPoint(x: self.bounds.midX, y: self.bounds.midY)
subview.transform = CGAffineTransform(scaleX: 1, y: 1)
}
}
subview.transform = CGAffineTransform(scaleX: 1, y: 1)
subview.transform = CGAffineTransform(scaleX: 2, y: 2)
subview.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
问题是,每次执行
subview.transform
时,layoutSubviews
函数也会被调用,并且子视图框架也会发生变化。如果没有动画或延迟,它实际上会转换回原始帧。你可以放一些animate
来检查:
UIView.animate(withDuration: 1) {
self.subview.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
}
为了避免这种情况,您必须将设置大小和框架移动到
init
,这样它就会被调用一次。然后从外部改造,也许是从ViewController
:
class ScalingView: UIView {
override init(frame: CGRect) {
...
let subviewSize = 100
subview.frame.size = CGSize(width: subviewSize, height: subviewSize)
subview.center = CGPoint(x: self.bounds.midX, y: self.bounds.midY)
}
func scaleSubView(_ scale: CGFloat = 1.5) {
UIView.animate(withDuration: 0.3) {
self.subview.transform = CGAffineTransform(scaleX: scale, y: scale)
}
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
scalingView.scaleSubView()
}