ios - 从 Nib 加载时 UIView 的帧大小?

标签 ios swift uiview interface-builder xib

我正在从这样的 .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/

相关文章:

android - 没有Phonegap构建的iOS Phonegap应用

ios - Swift:无法关闭模态呈现的 LoginViewController

swift - UIView 的 AirPrint 内容

iphone - touchesBegan - iPhone 应用程序 UIView

php mysql emoji 双字符

ios - 设备重启后的本地通知

ios - NSTimer 在 firedate 之前触发

objective-c - Objective-C 类别中的 Swift 协议(protocol)

Swift - 项目未显示在我的带有自定义单元格的表格 View 中

iphone - 在uiview上画直线