Reputation: 5789
I want to give a circular coloured background to a UIImageView
on a UICollectionViewCell
. To do this I am applying a cornerRadius
to the UIImageView
's layer
.
Obviously the cornerRadius
needs to be half the frame
's height/width. I'm putting this code in the layoutSubviews
method, which is probably wrong, because when it's called the image's frame
is huge. Rotating the phone and rotating it back solves the problem, because by then the frame
has been correctly set.
Where should I be putting the cornerRadius
calculation code?
Is there a better way of getting an image on a circular background anyway?
Note: The UIImageView
may change height/width during layout operations. I'm using Autolayout.
Code:
class EventPickerCell: UICollectionViewCell
{
@IBOutlet weak var image: UIImageView!
@IBOutlet weak var label: UILabel!
override func layoutSubviews()
{
super.layoutSubviews()
print("imagesizes = frame = \(image.frame), bounds = \(image.bounds)")
image.layer.cornerRadius = CGRectGetWidth(image.frame)/2
image.layer.backgroundColor = UIColor.whiteColor().CGColor
}
}
Upvotes: 0
Views: 813
Reputation: 568
You provide the cells to the collection view controller in func collectionView(collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
. This is where you configure the cell, so you should update the image layer here too.
If you want just a view to do this by itself, you could create a UIImageView subclass and watch for bounds
updates:
override var bounds: CGRect {
didSet {
// update layer here
}
}
Upvotes: 1
Reputation: 80781
You could always just subclass a UIImageView
in order to set the cornerRadius
when the frame
changes.
class CircularImageView : UIImageView {
override var frame: CGRect {
didSet { // frame did change
self.layer.cornerRadius = frame.size.width*0.5 // set corner radius
}
}
}
Upvotes: 1
Reputation: 483
Try cellForItemAtIndexPath.
You can instantiate your cell as EventPickerCell and have access to all its properties.
Another way would be to look into computed variables.
Something along those lines: Inside your cell:
var image: UIImage = UIImage() {
didSet {
imageView.image = image
imageView.layer.cornerRadius = image.size.width
}
this will set the corner radius as soon as you set the cells image.
Upvotes: -1