您好我正在使用这些代码
重新启动文本大小CGSize textSize = [self.text sizeWithFont:self.font
constrainedToSize:self.frame.size
lineBreakMode:self.lineBreakMode];
以上是贬值。我们怎样才能改变它以保持目的?
任何帮助都非常感谢。谢谢!
我的整个功能目的是对齐UIable top(垂直)
- (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];
}
答案 0 :(得分:2)
使用此
- (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;
}
我希望这会有所帮助