Search code examples
iosobjective-cswiftautolayoutnslayoutconstraint

Getting correct frame after setting constraint


I have a method that creates a mask layer based on the current frame of my UIImageView, which works as I expected. However, in one case, I modify the height constraint of a UIImageView in the viewWillAppear method, and then apply the mask creator to the UIImageView, which creates a mask with a worng size. So my question is, how can I force to get the modified correct frame of that UIImageView?

Right now I'm getting the height 140 insted of 105, but if I use layoutIfNeeded after setting the constraint it become 118, which is closer, but still not 105.

Updated:

The method that I use for creating the mask:

public func setupMaskForImageView() {
    let mask = CALayer()
    let resizedMaskImage = resizeImage(UIImage(named: imageMaskName)!, newSize: frame.size)
    mask.contents = resizedMaskImage
    mask.frame = CGRectMake(0, 0, frame.size.width, frame.size.height)
    layer.mask = mask
    layer.masksToBounds = true
}

and I modified the constraint in viewWillAppear with

imageHeight.constant = UIScreen.mainScreen().bounds.width / 2.5

Solution

  • It's always ideal to keep your framing kept in layoutSubviews. From the Apple developer UIKit doc:

    layoutSubviews - Implement this method if you need more precise control over the layout of your subviews than either the constraint or autoresizing behaviors provide.

    That being said, your best option is probably to create a subclass for your custom UIImageView and insert your reframing logic in layoutSubviews. This will ensure your view and mask are always properly framed.