How to add constraints to a Custom UITableViewCell

10.1k views Asked by At

I have created a custom cell for my table view and it works fine except that my Image View will not align correctly.

Is there a way to add constraints to a custom cell view? Programmatically or otherwise?

This is what my cell looks like in the storyboard - which is what I was hoping to achieve at run time:

But when I demo the app this is what happens:

Here is another image from the storyboard:

View Controller /w TableView

@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()


    println(questions)
    println(finalResults)

    let theWidth = view.frame.size.width
    let theHeight = view.frame.size.height

    tableView.frame = CGRectMake(0,0, theHeight, theWidth)
}

Cell View Controller

override func awakeFromNib() {

    let theWidth = UIScreen.mainScreen().bounds.width
    contentView.frame = CGRectMake(0,0, theWidth, 64)

    answerImage.center = CGPointMake(115, 15)
}
2

There are 2 answers

2
lchamp On BEST ANSWER

You only have to set up your constraints correctly. Indeed, even if Add Missing Constraints and Reset to Suggested Constraints are handy sometimes they don't know what you want, thus the result cannot always be what you expect.

What you might want to do here is the following.

For you question label set it in center Y of it's container and set it's leading space to the superview. Like so :

Center Y Leading Space

Then for you image, you want to set it in center Y of it's container too and set a ratio 1:1 on it. Like so :

Center Y Aspect Ratio

Note that you might also want to check the width and height if you don't want your image to upscale (if you set a bigger cell on some device).

You should now have something like that :

Storyboard

And the result :

Screen

Let me know if it helped.

PS : I don't have your image so I've just set a background color on the uiimageview

5
whereisleo On

Assuming that you started with a View Controller, Dragged a table and a Cell into the table...

in ViewController: UIViewController...{

@IBOutlet weak var resultsTable: UITableView! // connect to tableView

override func viewDidLoad() {
  super.viewDidLoad()

  let theWidth = view.frame.size.width
  let theHeight = view.frame.size.height

  resultsTable.frame = CGRectMake(0,0, theWidth, theHeight)
}
}

in UITableViewCell file:

@IBOutlet weak var imageView: UIImageView!

override func awakeFromNib() {

  let theWidth = UIScreen.mainScreen().bounds.width
  contentView.frame = CGRectMake(0,0 theWidth, 64)

  imageView.center = CGPointMake(115, 15) //mess around with these #
}