UIView从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))
}
链接地址: http://www.djcxy.com/p/82009.html

上一篇: Frame size of UIView when loaded from Nib?

下一篇: Creating and assigning CGRect to a UIView within a for loop