我正在从这样的 .xib 文件加载 UIView:
static func loadFromNib() -> CardView {
let nib = UINib(nibName: "CardView", bundle: nil)
return nib.instantiate(withOwner: self, options: nil).first as! CardView
}
加载时, View 具有在 Interface Builder 的大小检查器的“框架矩形”中设置的确切框架大小。
这是有保证的吗?我需要这个大小是准确的,因为 subview 约束是特定的,如果 View 大小错误 [*] 将不适合,但我在 Apple 的文档中没有找到任何提及。
[*] = 原因:我正在将 View 渲染到 UIImage,以便稍后可以在 UIImageView 中显示它。它显示成员(member)卡的图像,姓名和成员(member)编号需要在所有设备上以正确的字体大小显示在正确的位置..
最佳答案
将任何 UIView 子类设置为 xib 的所有者,然后加载 xib 作为该 View 的 subview 并设置自动调整掩码。
我是这样用的:
extension UIView {
func loadXibView(with xibFrame: CGRect) -> UIView {
let className = String(describing: type(of: self))
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: className, bundle: bundle)
guard let xibView = nib.instantiate(withOwner: self, options: nil)[0] as? UIView else {
return UIView()
}
xibView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
xibView.frame = xibFrame
return xibView
}
}
xibView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
正确设置 View 大小。
然后在初始化的任何 UIView 子类中使用它:
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(loadXibView(with: bounds))
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
addSubview(loadXibView(with: bounds))
}
关于ios - 从 Nib 加载时 UIView 的帧大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44269516/