layoutSubviews Confusion — Manipulating TMQuiltView

101 Views Asked by At

I'm trying out this custom class — TMQuiltView — https://github.com/1000Memories/TMQuiltView. Normally, I layout interfaces in Storyboard, and that's not an issue. Since this is a custom class, it appears as if I have to do so programatically.

I would have posted a screenshot of what comes in their demo, but I don't have enough reputation. Instead, I will show the -(void) layoutSubviews method

- (void)layoutSubviews {

self.photoView.frame = CGRectInset(self.bounds, kTMPhotoQuiltViewMargin, kTMPhotoQuiltViewMargin);
self.titleLabel.frame = CGRectMake(kTMPhotoQuiltViewMargin, self.bounds.size.height - 20 - kTMPhotoQuiltViewMargin, self.bounds.size.width - 2 * kTMPhotoQuiltViewMargin, 20);

}

My goal is to get that titleLabel to appear below the photoView, but I don't want it to be a definite size (i.e. I would have used autolayout if I were storyboarding). So, in the titleLabel's method, I tried to calculate the height of the label:

CGSize labelSize = [_titleLabel.text sizeWithFont:_titleLabel.font
                                constrainedToSize:_titleLabel.frame.size
                                    lineBreakMode:NSLineBreakByWordWrapping];

    labelHeight = labelSize.height;

But here's where I'm running into a dead-end. I can't use this in making a CGRect (CGPoint is incompatible). Do I make a CGRect for the image somewhere? How do I define it in relation to self.bounds?

1

There are 1 best solutions below

3
On BEST ANSWER
  1. Don't forget to call [super layoutSubviews]; in layoutSubviews method.
  2. sizeWithFont:constrainedToSize:lineBreakMode: is deprecated in iOS8
  3. you can use _titleLabel.lineBreakMode in your calculating method

Ofc you can use this size in your method eg via:

CGRectMake(origin.x, origin.y, size.width, size.height);

To help you to code it I need to clarify: You want to have an imageView which is above label and the label should resize depending on text size?

Ad3. You can use such method instead (source: GitHub opensource library):

- (CGSize)ios67sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size {
    CGSize textSize;
    if ([self respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
        textSize = [self boundingRectWithSize:size options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) attributes:@{NSFontAttributeName:font} context:nil].size;
    } else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        textSize = [self sizeWithFont:font constrainedToSize:size];
#pragma clang diagnostic pop
    }

    return textSize;
}