简体   繁体   中英

iOS analog for inflating a view from a layout (xib)

I'm new to iOS and trying to rewrite an app from android. What I do in Android - I have a layout - same as nib in xcode

在此输入图像描述

And then I inflate this view as many times I want - same as ListView (TableView's android analog) is working

I need to do this on iOS : 在此输入图像描述

which means having some container like Android's horisontal LinearLayout where I can add nib's with their class - like UITableViewCell and fill data. When I asked one person who is iOS developer, he told me that it is almost impossible to do due to compexity and lack of android-like ViewGroups and that it's better to do in a WebView than natively.

So please, tell me , is there a solution - to inflate as many views as needed from a nib into container-views one under another ? Please answer in Swift, I don't know Obj-c at all

Yes you can do it by registering your tableView with Xib in viewDidLoad

tableView.registerNib(UINib(nibName: "CustomCellXib", bundle: nil), forCellReuseIdentifier: "CustomCell")

Then do this in delegate method

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

        cell.middleLabel.text = items[indexPath.row]
        cell.leftLabel.text = items[indexPath.row]
        cell.rightLabel.text = items[indexPath.row]

        return cell
    }

where CustomCellXib is your Xib file name. CustomCell is your class of CustomCellXib and @"CustomCell" is string identifier for reusing cells

Note down that you will have to implement other few delegates methods too for complete working of TableView.

There is nothing extremely complex here. It's a common UITableView with multiple sections.

  1. Red text labels for every sections should be implemented as section headers

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    //create a view here
}
  1. Custom UITableViewCell with grey labels, red - and + buttons in it.
  2. Custom cell should contain a UIImageView below it's content. Since it is different for first, middle and last rows, you should set one of three images in cellForRow method depending on the cell's indexPath.row.

PS Don't listen to your iOS developer. You should not use UIWebView whenever you need to implement UI a bit more complex than default UITableView . Most probably he was joking ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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