我想为CGSize
获得NSString
,但我遇到了问题。这是我正在使用的代码:
CGFloat actualMessageFontSize;
CGSize messageSize =
[message sizeWithFont:[UIFont fontWithName:@"Helvetica-Bold"
size:14.0f]
minFontSize:14.0f
actualFontSize:&actualMessageFontSize
forWidth:(alertViewWidth - textIndent)
lineBreakMode:NSLineBreakByWordWrapping];
我NSLog
此代码之后的CGSize
并且高度不会改变,即使我将大量NSString
放入其中。你知道为什么会发生这种情况,或者我应该尝试做什么呢?
感谢。
答案 0 :(得分:2)
使用此方法和
-(float) calculateHeightOfTextFromWidth:(NSString*) text: (UIFont*)withFont: (float)width :(UILineBreakMode)lineBreakMode
{
[text retain];
[withFont retain];
CGSize suggestedSize = [text sizeWithFont:withFont constrainedToSize:CGSizeMake(width, FLT_MAX) lineBreakMode:lineBreakMode];
[text release];
[withFont release];
return suggestedSize.height;
}
并像下面一样使用它...我将此用于UILable
,请参阅代码..
UILabel *lblAddress = [[UILabel alloc]init];
[lblAddress setFrame:CGRectMake(110, 31, 200, 31)];
lblAddress.text = @"ABDKFNKG KKGK jfnjgdf gdklfg fldgmfkgml f";
lblAddress.lineBreakMode = UILineBreakModeWordWrap;
lblAddress.numberOfLines = 0;///write this line for multiple line and set 0 or anything lese
lblAddress.font = [UIFont fontWithName:@"Helvetica" size:12];
lblAddress.frame = CGRectMake(lblAddress.frame.origin.x, lblAddress.frame.origin.y,
200,[self calculateHeightOfTextFromWidth:lblAddress.text :lblAddress.font :200 :UILineBreakModeWordWrap] );
lblAddress.textColor = [UIColor darkGrayColor];
[self.view addSubview:lblAddress];
答案 1 :(得分:0)
您有UILabel
或UITextView
的更改框架,他们可能会使用相应的更改。
CGFloat actualMessageFontSize = 12.0;
CGSize messageSize = [message sizeWithFont:[UIFont fontWithName:@"Helvetica-Bold" size:14.0f] minFontSize
//set frame accordingly
yourLabel.frame = CGReactMake(yourLabel.frame.origin.x,yourLabel.frame.origin.y,messageSize.width,messageSize.wiheight,);