Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add view to a cell in a Table View Programmatically

I have a table view with dynamic prototypes that is currently displaying 4 elements programmatically. I assign the cell names through an array (see code below), but I also want to add a small view to the right half of each cell in order to show a small graph next to each label. I can drop in a view in storyboard, but it doesn't extend itself dynamically. Basically I need to find a way to modify this code to add a view inside of each cell and assign a class I have already created to those views.

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("LineCell", forIndexPath: indexPath) as! UITableViewCell
    cell.textLabel?.text = oneLine.lineNames[indexPath.row]
    return cell
}

This is where I want the views:

enter image description here

Also, how can I make more space between the Carrier, Time, and Battery and the table view?

like image 459
mattgabor Avatar asked Dec 05 '22 03:12

mattgabor


2 Answers

You can create the view as you want and add it as subview of your cell's contentView:

var newView = UIView(frame: CGRectMake(200, 10, 100, 50))
cell.contentView.addSubview(newView)
like image 186
Henrique Barros Avatar answered Dec 19 '22 08:12

Henrique Barros


To add "Space" between your tableView and the status bar you can embedded your tableviewcontroller in a uinavigationconttoller.

To add a view dynamically you can use the method addSubview on your cell and add constraints in your code with the auto layout

like image 37
Kakahn Avatar answered Dec 19 '22 08:12

Kakahn