UITableViewCell as UIView from XIB

霸气de小男生 提交于 2020-08-25 05:17:53

问题


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
}

回答1:


There is one way you can use contentView property of UITableViewCell which of type UIView. So simply get RestaurantTableViewCell as you previously getting from nib then use its contentView to get the UIView from it.

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



回答2:


Try this code :

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


来源:https://stackoverflow.com/questions/43650719/uitableviewcell-as-uiview-from-xib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!