ios - 从 XIB 加载 View 到 ViewController 和 VIewCell

标签 ios swift xib nib

我有一个带有自定义类 ProfileHeaderView 的 XIB。 我还有 ProfileViewControllerProfileTableViewCell,它们都带有 IBOutlet profileHeader

我想要的是将 nib 加载到 profileHeader 中。到目前为止,我通过加载 NIB 然后将其添加为 profileHeader 的 subview 来实现,我认为这不是最佳解决方案,我必须手动设置框架。

let view = NSBundle.mainBundle().loadNibNamed("ProfileHeaderView", owner: self, options: nil).last as! ProfileHeaderView
view.setFrame(...)
self.profileHeaderView.addSubview(self.view)

实现它的最佳方法是什么?

最佳答案

首先,创建自定义 View 类

class CustomView: UIView {

    // MARK: Custom View Initilization
    var view: UIView!

    func xibSetup() {
        view = loadViewFromNib()
        view.frame = bounds
        view.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
        addSubview(view)
        //// additional setup here
    }
    func loadViewFromNib() -> UIView {
        let bundle = NSBundle(forClass: self.dynamicType)
        // set nibName to be xib file's name
        let nib = UINib(nibName: "CustomView", bundle: bundle)
        let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
        return view
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        xibSetup()
    }
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        xibSetup()
    }

}

其次,在 CustomView.xib 中将 File's owner 自定义类设置为 CustomView


之后,你就完成了。您可以以编程方式创建自定义 View 。

let customView = CustomView(frame: frame)
self.view.addSubview(customView)

或者使用 Storyboard,将 UIView 拖到 ViewController 并将 UIView 的自定义类设置为 CustomView

关于ios - 从 XIB 加载 View 到 ViewController 和 VIewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31358675/

相关文章:

ios - swift - 应用程序购买

ios - 如何根据用户选择更新应用程序的整个 UI?

ios - swift 将 CLLocation 转换为 CLLocationCoordinate2D

ios - tableViewController 上的自动调整 View 大小

swift - 在 [String:String] 中转换 [(key : String, value: String)]

ios - Xcode Storyboard 中的 "Inferred"和 "Freeform"有什么区别?

iphone - 加载 xib 文件

ios - 在 iPad 应用程序和 iPhone 之间使用 iBeacon 和 Passbook 是否可以识别此人?

ios - 自动调用用户位置

ios - 将 .xib 文件放在框架项目中的什么位置?