Lê Khánh Vinh
Lê Khánh Vinh

Reputation: 2611

IOS create textsize with CGSize depreciated method

Hi i am reacreating the textsize with these code

CGSize textSize = [self.text sizeWithFont:self.font
                        constrainedToSize:self.frame.size
                            lineBreakMode:self.lineBreakMode];

the above is depreciate. how can we change it inorder to keep the purpose?

Any help is much appreciate. Thanks!

My whole function purpose is to align the UIlable top (vertical)

- (void)alignTop
{
    CGSize textSize = [self.text sizeWithFont:self.font
                            constrainedToSize:self.frame.size
                                lineBreakMode:self.lineBreakMode];

    CGRect textRect = CGRectMake(self.frame.origin.x,
                                 self.frame.origin.y,
                                 self.frame.size.width,
                                 textSize.height);
    [self setFrame:textRect];
    [self setNeedsDisplay];
}

Upvotes: 0

Views: 213

Answers (1)

Reinier Melian
Reinier Melian

Reputation: 20804

Use this

 - (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(nullable NSDictionary<NSString *, id> *)attributes context:(nullable NSStringDrawingContext *)context

OR use this

 - (CGSize)sizeWithAttributes:(nullable NSDictionary<NSString *, id> *)attrs

this is an example

+ (CGSize)neededSizeForText:(NSString*)text withFont:(UIFont*)font andMaxWidth:(float)maxWidth
{
    NSStringDrawingOptions options = (NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin);

    NSMutableParagraphStyle * style =  [[NSMutableParagraphStyle alloc] init];
    [style setLineBreakMode:NSLineBreakByWordWrapping];
    [style setAlignment:NSTextAlignmentRight];

    NSDictionary *textAttibutes = @{NSFontAttributeName : font,
                                    NSParagraphStyleAttributeName : style};

    CGSize neededTextSize = [text boundingRectWithSize:CGSizeMake(maxWidth, 500) options:options attributes:textAttibutes context:nil].size;

    return neededTextSize;
}

I hope this helps

Upvotes: 2

Related Questions