UITableViewCell as UIView from XIB

时间:2017-04-27 06:59:24

标签: ios uitableview uiview xib nscoder

I have CustomTableViewClass in XIB, adding it to UITableView like

class RestaurantsTableView: UITableView {
    override func awakeFromNib() {
        self.register(UINib(nibName: "RestaurantTableViewCell", bundle: nil), forCellReuseIdentifier: "restaurantCell")
    }
}

and everything works fine, now I would like to use this CustomTableViewClass as UIView in some other UIViewController, but I do not get how to properly override its init(coder aCoder: NSCoder) function, cause I do not need one for UITableView case and when I implement it like I do for other custom XIB views it crashes with nil

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    let _ = Bundle.main.loadNibNamed("RestaurantTableViewCell", owner: self, options: nil)?[0] as! UIView
}

2 个答案:

答案 0 :(得分:6)

有一种方法可以使用UITableViewCell的{​​{1}}属性UIView。 因此,只需获取之前从nib获取的RestaurantTableViewCell,然后使用其contentView从中获取UIView

let cell = Bundle.main.loadNibNamed("RestaurantTableViewCell", owner: self, options: nil)?[0] as! RestaurantTableViewCell
let yourView = cell.contentView

答案 1 :(得分:0)

试试这段代码:

    var views:NSArray = NSBundle.mainBundle().loadNibNamed("Your_Xib_file", owner: self, options: nil);
    var yourView:UIView = views.objectAtIndex(0) as! UIView;