2

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
7
  • 1
    I try to keep the majority of my framing in layoutSubviews. Have you tried setting the frame there so it's updated whenever views are need reframing? Commented Apr 24, 2015 at 18:10
  • @joels The view which I try to set its frame is not a sublcass of UIView, so setting in layoutSubviews is not available unfortunately. Commented Apr 24, 2015 at 18:14
  • How do you add the mask and how do you update its constraint. Commented Apr 24, 2015 at 18:59
  • What is the relationship between layer and the imageView. Did you mean that the layer frame is not equal to the imageView's? Commented Apr 24, 2015 at 19:21
  • 1
    Ok, I can't help because I don't know how you set up your imageView and layer. The only thing I can tell is that you need a way to know when your imageView frame changed and notify to update layer's frame. I suggest you update layer's frame in viewDidLayoutSubviews of your view controller Commented Apr 24, 2015 at 19:40

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.