[英]Frame size of UIView when loaded from Nib?
我正在從.xib文件加載UIView,如下所示:
static func loadFromNib() -> CardView {
let nib = UINib(nibName: "CardView", bundle: nil)
return nib.instantiate(withOwner: self, options: nil).first as! CardView
}
加載時,視圖具有在Interface Builder中Size Inspector的“Frame Rectangle”中設置的確切幀大小。
這有保證嗎? 我需要這個大小是准確的,因為子視圖約束是特定的,如果視圖的大小錯誤[*]則不適合,但我在Apple的文檔中沒有發現任何提及。
[*] =原因:我將視圖渲染為UIImage,以便稍后可以在UIImageView中顯示它。 它顯示了會員卡的圖像,並且名稱和會員編號需要在所有設備上的正確字體大小的正確位置。
為您的UIView創建一個自定義類:
class CardView: UIView {
override init(frame: CGrect) {
super.init(frame: frame)
let xibView = UINib(nibName: "CardView", bundle: nil).instantiate(withOwner: nil, options:nil)[0] as! UIView
self.addSubview(xibView)
}
require init?(coder: aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
然后從類中調用if您將使用您需要的幀大小實現它,否則它將默認為您在界面構建器中設置的大小:
// MyViewController
var cardView: CardView?
override func viewDidLoad() {
super.viewDidLoad()
self.cardView = CardView()
self.cardView.frame.size = CGSize(size here)
self.cardView.frame.origin = CGPoint(point here)
self.view.addSubview(self.cardView!)
}
將任何UIView子類設置為xib的所有者,然后將xib作為此視圖的子視圖加載並設置自動調整掩碼。
這就是我使用它的方式:
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]
正確設置視圖大小。
然后在初始化中使用任何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))
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.