简体   繁体   English

如何在 Swift 中以编程方式将 HeaderView 从 nib 添加到 UiTableView

[英]How to Add HeaderView from nib to UiTableView programmatically in Swift

Well i'm a naive IOS developer using swift language.好吧,我是一个使用 swift 语言的天真的 IOS 开发人员。

I have a table view which displays a list of features of a hotel.Now i want to add a header information to the tableView with hotel image, hotel name above the tableview so that the header information also scrolls along with tableview contents(product features list)我有一个显示酒店功能列表的表视图。现在我想将标题信息添加到带有酒店图像的 tableView,tableview 上方的酒店名称,以便标题信息也随着 tableview 内容滚动(产品功能列表)

Here is the problem, TableView with list of features is working fine.这是问题所在,带有功能列表的 TableView 工作正常。

class HotelDetailViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {

    @IBOutlet weak var categoriesTableView: UITableView!

    var items: [(String, String,String)] = [
        ("Service", "   Courteous service, Good staff , Good staff","   Bad Facility"),
        ("Vibe",  "   Courteous service, Good staff","   Bad Facility"),
        ("Hotel",  "   Courteous service, Good staff","   Bad Facility"),
        ("Room Facility",  "   Courteous service, Good staff","   Bad Facility"),
        ("Amenities",  "   Courteous service, Good staff","   Bad Facility"),
        ("Food", "   Courteous service, Good staff","   Bad Facility")
    ]


    override func viewDidLoad() {
        super.viewDidLoad()
        let nib = UINib(nibName: "HotelSnippetTableViewCell", bundle: nil)
        categoriesTableView.separatorStyle = UITableViewCellSeparatorStyle.None
        categoriesTableView.registerNib(nib, forCellReuseIdentifier: "CustomCell")
        categoriesTableView.rowHeight = UITableViewAutomaticDimension
        categoriesTableView.estimatedRowHeight = 100    
    }



    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let customTableViewCell = tableView.dequeueReusableCellWithIdentifier("CustomCell") as! HotelSnippetTableViewCell

        let info  = items[indexPath.row]

        customTableViewCell.setCategory(info.0)

        customTableViewCell.setPositive(info.1)
        customTableViewCell.setNegative(info.2)


        return customTableViewCell

    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        print("You selected cell #\(indexPath.row)!")

    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }


}

For header information like hotelImage , hotel name and other labels i have created a nib with all the views set and a corresponding class with all the references mapped to it.对于像 hotelImage 、酒店名称和其他标签这样的标题信息,我创建了一个带有所有视图集的笔尖和一个对应的类,其中所有引用都映射到它。

Now how to add this UiView to my tableview as a header programatically (because i get data after rest call).现在如何以编程方式将此 UiView 作为标题添加到我的 tableview 中(因为我在 rest 调用后获取数据)。

I have searched but found tutorials on how to set string section headers.我已经搜索过,但找到了有关如何设置字符串部分标题的教程。

Couple of things i tried out:我尝试过的几件事:

  1. I found that there is a protocol function for TableView发现有TableView的协议函数

    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { //Code}

But how to load my nib here and set to this tableview and also i want ti trigger this programatically only after getting the data from service但是如何在此处加载我的笔尖并设置为该表视图,并且我希望仅在从服务获取数据后以编程方式触发此操作

  1. Create a nib with parent as TableViewCell, Load it using dequeueReusableCellWithIdentifier(), set info and set to tableview创建一个以父为 TableViewCell 的笔尖,使用 dequeueReusableCellWithIdentifier() 加载它,设置 info 并设置为 tableview

     let headerCell = categoriesTableView.dequeueReusableCellWithIdentifier("HotelDetailHeaderTableViewCell") as! HotelDetailHeaderTableViewCell headerCell.setImageUrl(""); headerCell.setHotelZmi(CGFloat(87)) headerCell.setNameAndPersona("Fort Aguada Goa", persona: "OverAll", reviewsCount: "780") headerCell.frame = CGRectMake(0, 0, self.categoriesTableView.bounds.width, 600) categoriesTableView.tableHeaderView = headerCell

But even this is throwing some exception and i can't see where the exception is(How to see exception log in Xcode?).但即使这会引发一些异常,我也看不到异常在哪里(如何在 Xcode 中查看异常日志?)。

Is the process i'm doing is correct?我正在做的过程是否正确? If not anyone please suggest me efficient approach如果不是任何人,请建议我有效的方法

Because in Android i used to create a NestedScrollView with linear layout inside it embedded with any number of recyclerViews(removing scroll for recyclerviews) and Relativelayout因为在 Android 中,我曾经创建一个 NestedScrollView,里面有线性布局,里面嵌入了任意数量的 recyclerViews(移除了 recyclerviews 的滚动)和 Relativelayout

Please Help me.请帮助我。

You can use this code to init your nib file您可以使用此代码来初始化您的 nib 文件

let view = (Bundle.main.loadNibNamed("MenuHeader", owner: self, options: nil)![0] as? UIView)

tableView.tableHeaderView = view

Then your MenuHeader will be a normal .xib file with your cell inside it, just remember to adjust the constraints appropriately to fit on all the screens that you want.然后您的 MenuHeader 将是一个普通的 .xib 文件,其中包含您的单元格,只需记住适当调整约束以适合您想要的所有屏幕。

Update for swift 4 Swift 4 的更新

let view = (Bundle.main.loadNibNamed("TableViewHeader", owner: self, options: nil)![0] as? UIView) 
self.tableview.tableHeaderView = view

I would recommend using the UITableViewDelegate methods of tableView( :viewForHeaderInSection:) and tableView( :heightForHeaderInSection:).我建议使用 tableView( :viewForHeaderInSection:) 和 tableView( :heightForHeaderInSection:) 的 UITableViewDelegate 方法。

You can then do the following:然后,您可以执行以下操作:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = Bundle.main.loadNibNamed("ExampleTableHeaderView", owner: self, options: nil)?.first as? UIView
    return headerView
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 10
}

Other answers involve force unwrapping (!) and placing in brackets which is not necessary.其他答案涉及强制展开(!)并放在括号中,这是不必要的。

In your viewForHeaderInSection load the custom view from xib and return it在您的viewForHeaderInSectionviewForHeaderInSection加载自定义视图并返回它

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    // for example you have xib as 'CustomHeaderView.xib'
    let headerView = CustomView()
    headerView.myLabel.text = "My Title"

    return headerView
}

Another method is specifying the header height另一种方法是指定标题高度

func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 60.0 // put your height here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM