IOS 使用 CGSize 弃用方法创建文本大小

IOS create textsize with CGSize depreciated method

您好,我正在使用这些代码重新创建文本大小

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

以上为贬值。我们怎样才能改变它以保持目的?

非常感谢任何帮助。谢谢!

我的整个功能目的是对齐 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];
}

使用这个

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

或使用此

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

这是一个例子

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

希望对您有所帮助