我已经研究了2天,但我还没有找到解决这个问题的方法:
我正在从Xib加载视图,并对其应用自动布局。视图显示正确,自动布局工作正常。但是当我尝试在自动布局后获取子视图的框架时,它无法正常工作。我需要子视图的框架来制作redView
圆形。
我在初始化时从Xib加载视图并将其添加为带有自动布局的子视图(我已经尝试了很多不同的东西并检查我正在做的打印是否在layoutSubviews
。< / p>
class ReusableView: UIView {
@IBOutlet weak var redView: UIView!
var mainView: UIView?
// MARK: - Initializers.
override init(frame: CGRect) {
super.init(frame: frame)
loadXIB()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
loadXIB()
}
override func layoutSubviews() {
super.layoutSubviews()
print ("Self subviews \(self.subviews)")
print ("MainView frame \(mainView?.frame)")
print ("Red View frame \(redView?.frame)")
}
func loadXIB() {
guard let view = loadView(String(describing: type(of: self))) else { return }
print ("View loaded from nib \(view.frame)")
view.translatesAutoresizingMaskIntoConstraints = false
view.subviews.forEach {
$0.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
addSubview(view)
NSLayoutConstraint.activate([
view.topAnchor.constraint(equalTo: self.topAnchor),
view.leadingAnchor.constraint(equalTo: self.leadingAnchor),
view.trailingAnchor.constraint(equalTo: self.trailingAnchor),
view.bottomAnchor.constraint(equalTo: self.bottomAnchor),
])
mainView = view
}
func loadView(_ nibName: String) -> UIView? {
if nibName.isEmpty {
return nil
}
let bundle = Bundle(for: type(of: self) as AnyClass)
let nib = UINib(nibName: nibName, bundle: bundle)
if let view = nib.instantiate(withOwner: self, options: nil).first as? UIView {
return view
}
return nil
}
}
印刷品的结果:
View loaded from nib (0.0, 0.0, 375.0, 667.0)
Self subviews [<UIView: 0x7ff232216880; frame = (0 0; 150 150); autoresize = W+H; layer = <CALayer: 0x60800022f4e0>>]
MainView frame Optional((0.0, 0.0, 150.0, 150.0))
Red View frame Optional((0.0, 20.0, 375.0, 647.0))
MainView subviews Optional([<UIView: 0x7ff232216690; frame = (0 20; 375 647); autoresize = W+H; layer = <CALayer: 0x60800022f520>>])
正如我们所看到的,mainView已经调整大小但不是他的子视图。 (然后当打印视图时它完全正常,我一直在使用更复杂的视图,但我从来没有遇到过在de UIView中获取框架的问题。)