Pradip Kumar Pradip Kumar - 4 months ago 25
Swift Question

Add TableView into .xib View in swift

On clicking button I have a .xib view in which I define a tableView.Here for cell I create another .xib file because there is only option . no default cell is there I think.. so How can I display the items in tableview cell.
I have registered the .Xib like this and tried but surprising view I got.

class CustomAddOnVC: UIViewController,UITableViewDataSource,UITableViewDelegate {

let items = ["pk","ak","sk"]

override func viewDidLoad() {
super.viewDidLoad()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

let identifier = "Cell"
var cell: CustomOneCell! = tableView.dequeueReusableCellWithIdentifier(identifier,forIndexPath: indexPath) as? CustomOneCell
if cell == nil {
tableView.registerNib(UINib(nibName: "CustomOneCell", bundle: nil), forCellReuseIdentifier: identifier)
cell = tableView.dequeueReusableCellWithIdentifier(identifier,forIndexPath:indexPath ) as? CustomOneCell
cell.addOnName.text = items[indexPath.row]
cell.addOnPrice.text = "£0.0"
}

return cell
}


Here the items counting came as 3 but the data is populating in the first one only.

screenshot

enter image description here

And one more thing How can I set the the height of view till the end of all items?? As you can see extra space after the items. If i decrease the size and more items came then again same problem.I want to set the height dynamically according to the items data

Answer

I think it is because it does not enter your cell == nil anymore as you register for the first time. Therefore, my suggestion is to move your updating text outside the if statement. Like this:

if cell == nil {
    tableView.registerNib(UINib(nibName: "CustomOneCell", bundle: nil), forCellReuseIdentifier: identifier)
    cell = tableView.dequeueReusableCellWithIdentifier(identifier,forIndexPath:indexPath ) as? CustomOneCell
}
cell.addOnName.text = items[indexPath.row]
cell.addOnPrice.text = "£0.0"`