简体   繁体   English

iOS使用CGSize折旧方法创建textsize

[英]IOS create textsize with CGSize depreciated method

Hi i am reacreating the textsize with these code 嗨,我正在用这些代码重新创建textsize

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) 我的整个功能目的是对齐UIlable顶部(垂直)

- (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];
}

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 我希望这有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM