通过Xib创建View

2016-10-11  本文已影响125人  T92

步骤
1.创建一个继承自UIView的view

2.创建Xib文件


3.关联文件


4.运用


bug解决
如果

self.headerView = nib.instantiateWithOwner(self, options: nil).first as! FilmDetailHeaderView

运行报错,就将继承自UIView的view的名字和关联名字改其他的运行一遍,然后再改回来

更好的方式:

1.创建一个继承自UIView的view

2.创建Xib文件

3.关联文件(选中File's Owner,将class设置为创建的view的名字)


4.将整个view拖到文件关联


5.文件内代码:

import UIKit

class APNView: UIView {

    @IBOutlet var contentView: UIView!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.initialFromXib()
    }
    
    required init?(coder aDecoder: NSCoder) {
        //fatalError("init(coder:) has not been implemented")
        super.init(coder: aDecoder)
        self.initialFromXib()
    }
    
    func initialFromXib() {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: "APNView", bundle: bundle)
        contentView = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
        contentView.frame = bounds
        addSubview(contentView)
    }

}

6.运用
运用方法和系统API提供的UIView方法相同,初始化方法都一样

上一篇 下一篇

猜你喜欢

热点阅读