KevinS KevinS - 4 months ago 22
iOS Question

How do I get the imageView's frame size during cellForRowAtIndexPath?

I'm trying to use a

UITableViewController
with a XIB, not a Storyboard, and use the default style:
UITableViewCellStyleDefault
. I want to set the default
imageView
's
cornerRadius
to the
imageView
's width / 2, but during
cellForRowAtIndexPath()
the
imageView
is 0,0,0,0.

I remember reading somewhere that the frame doesn't get updated until it is added to the sub view.

How to I get the
imageView.frame.size.width
? The
UITableView
is showing the rows correctly, but the
cornerRadius
is 0.

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

// Set Image
cell.imageView?.image = UIImage.init(imageLiteral: "\(indexPath.row).jpg")

// FOLLOWING DOESNT WORK imageView is 0,0,0,0
cell.imageView?.layer.cornerRadius = cell.imageView!.frame.size.width / 2

cell.imageView?.clipsToBounds = true
cell.imageView?.layer.masksToBounds = true

// Set Label
let name:String = contactsArray![indexPath.row] as! String
cell.textLabel!.text = name

return cell
}

Answer

One possible way to achieve your goal:
Subclass the UITableViewCell, and override layoutSubviews():

override func layoutSubviews() {
    super.layoutSubviews()
    self.imageView?.layer.cornerRadius = cell.imageView!.frame.size.width / 2
}
Comments