sizeWithFont 메소드는 더 이상 사용되지 않습니다. boundingRectWithSize가 예기치 않은 값을 반환합니다.
iOS7에서는 sizeWithFont
더 이상 사용되지 않으므로 boundingRectWithSize
(CGRect 값을 반환하는) 사용하고 있습니다. 내 코드 :
UIFont *fontText = [UIFont fontWithName:[AppHandlers zHandler].fontName size:16];
// you can use your font.
CGSize maximumLabelSize = CGSizeMake(310, 9999);
CGRect textRect = [myString boundingRectWithSize:maximumLabelSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:fontText}
context:nil];
expectedLabelSize = CGSizeMake(textRect.size.width, textRect.size.height);
에서를 사용할 때와 다른 크기 인 textRect
내 . 이 문제를 어떻게 해결할 수 있습니까?maximumLabelSize
sizeWithFont
새 라벨을 만들고 사용하는 것은 어떻습니까 sizeThatFit:(CGSize)size
??
UILabel *gettingSizeLabel = [[UILabel alloc] init];
gettingSizeLabel.font = [UIFont fontWithName:@"YOUR FONT's NAME" size:16];
gettingSizeLabel.text = @"YOUR LABEL's TEXT";
gettingSizeLabel.numberOfLines = 0;
gettingSizeLabel.lineBreakMode = NSLineBreakByWordWrapping;
CGSize maximumLabelSize = CGSizeMake(310, CGFLOAT_MAX);
CGSize expectSize = [gettingSizeLabel sizeThatFits:maximumLabelSize];
편집 :이 상위 코드는 iOS 7 이상에 적합하지 않으므로 아래를 사용하십시오.
CGRect textRect = [myString boundingRectWithSize:maximumLabelSize
options:NSStringDrawingUsesLineFragmentOrigin| NSStringDrawingUsesFontLeading
attributes:@{NSFontAttributeName:fontText}
context:nil];
이 답변 에서 제안하는 방법에 추가 옵션을 제공해야 할 수도 있습니다 .
CGSize maximumLabelSize = CGSizeMake(310, CGFLOAT_MAX);
CGRect textRect = [myString boundingRectWithSize:maximumLabelSize
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
attributes:@{NSFontAttributeName: fontText}
context:nil];
내 작업 코드 스 니펫은 다음과 같습니다.
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:attributeDict];
NSString *headline = [dict objectForKey:@"title"];
UIFont *font = [UIFont boldSystemFontOfSize:18];
CGRect rect = [headline boundingRectWithSize:CGSizeMake(300, 1000) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:nil];
CGFloat height = roundf(rect.size.height +4)
계산 된 높이에 4px를 추가했습니다.이 4px가 없으면 한 줄이 누락 되었기 때문입니다.
이 코드 조각을 tableView에서 사용하고 NSNumbers 배열에 "높이"를 추가하면 기본 textLabel에 대한 올바른 셀 높이를 얻습니다.
textLabel의 텍스트 아래에 더 많은 공간을 원하면 4 픽셀을 더 추가합니다.
**** 업데이트 ****
나는 "40px의 너비 버그"에 동의하지 않습니다. 4px가 글자와 한 줄의 경계 사이의 기본 높이이기 때문에 누락 된 높이의 4px라고 외칩니다. UILabel로 확인할 수 있으며, 글꼴 크기가 16 인 경우 UILabel 높이가 20이 필요합니다.
그러나 마지막 줄에 "g"가 없거나 그 안에 아무것도 없으면 측정 값이 4px 높이를 놓칠 수 있습니다.
나는 약간의 방법으로 그것을 다시 확인했고, 내 라벨의 정확한 높이는 20,40 또는 60이고 오른쪽 너비는 300px 미만입니다.
iOS6 및 iOS7을 지원하려면 내 방법을 사용할 수 있습니다.
- (CGFloat)heightFromString:(NSString*)text withFont:(UIFont*)font constraintToWidth:(CGFloat)width
{
CGRect rect;
float iosVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
if (iosVersion >= 7.0) {
rect = [text boundingRectWithSize:CGSizeMake(width, 1000) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:nil];
}
else {
CGSize size = [text sizeWithFont:font constrainedToSize:CGSizeMake(width, 1000) lineBreakMode:NSLineBreakByWordWrapping];
rect = CGRectMake(0, 0, size.width, size.height);
}
NSLog(@"%@: W: %.f, H: %.f", self, rect.size.width, rect.size.height);
return rect.size.height;
}
**** 업그레이드 ****
Thanks to your comments, I upgraded my function as followed. Since sizeWithFont is deprecated and you will get a warning in XCode, I added the diagnostic-pragma-code to remove the warning for this particular function-call/block of code.
- (CGFloat)heightFromStringWithFont:(UIFont*)font constraintToWidth:(CGFloat)width
{
CGRect rect;
if ([self respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
rect = [self boundingRectWithSize:CGSizeMake(width, 1000) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:nil];
}
else {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
CGSize size = [self sizeWithFont:font constrainedToSize:CGSizeMake(width, 1000) lineBreakMode:NSLineBreakByWordWrapping];
rect = CGRectMake(0, 0, size.width, size.height);
#pragma GCC diagnostic pop
}
return ceil(rect.size.height);
}
In addition to the 4px topic: depending which font and font-weight you use, the calculation returns different height-values. In my case: HelveticaNeue-Medium with a fontsize of 16.0 returns a line-height of 20.0 for a single line but 39.0 for two lines, 78px for 4 lines --> 1px missing for every line - beginning with line 2 - but you want to have your fontsize + 4px linespace for every line you have to get a height-result.
Please keep that in mind while coding!
I don´t have a function yet for this "problem" but I will update this post when I´m finished.
If I understand correctly, you are using boundingRectWithSize: just as a way of getting the size you would get with sizeWithFont (meaning you want directly the CGSize, not the CGRect)?
This looks like what you are looking for :
Replacement for deprecated sizeWithFont: in iOS 7?
They are using sizeWithAttributes: to get the size, as a replacement for sizeWithFont.
Do you still get the wrong size using something like this :
UIFont *fontText = [UIFont fontWithName:[AppHandlers zHandler].fontName size:16];
// you can use your font.
expectedLabelSize = [myString sizeWithAttributes:@{NSFontAttributeName:fontText}];
The @SoftDesigner's comment has worked for me
CGRect descriptionRect = [description boundingRectWithSize:CGSizeMake(width, 0)
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:12]}
context:nil];
result = ceil(descriptionRect.size.height);
for finding size of label run time sizewithfont is deprecated for iOS 7.0 instead of that you have to use -boundingRectWithSize:options:attributes:context: method
you can use it like below code
CGSize constraint = CGSizeMake(MAXIMUM_WIDHT, TEMP_HEIGHT);
NSRange range = NSMakeRange(0, [[self.message body] length]);
NSDictionary *attributes = [YOUR_LABEL.attributedText attributesAtIndex:0 effectiveRange:&range];
CGSize boundingBox = [myString boundingRectWithSize:constraint options:NSStringDrawingUsesFontLeading attributes:attributes context:nil].size;
int numberOfLine = ceil((boundingBox.width) / YOUR_LABEL.frame.size.width);
CGSize descSize = CGSizeMake(ceil(boundingBox.width), ceil(self.lblMessageDetail.frame.size.height*numberOfLine));
CGRect frame=YOUR_LABEL.frame;
frame.size.height=descSize.height;
YOUR_LABEL.frame=frame;
here you have to give width to maximum length for finding height or width.
try this it is working for me.
'program tip' 카테고리의 다른 글
Composer-요청한 PHP 확장 mbstring이 시스템에 없습니다. (0) | 2020.10.09 |
---|---|
클릭시 확인란이 선택되어 있지 않은지 확인하십시오-jQuery (0) | 2020.10.09 |
numpy std ()가 matlab std ()에 다른 결과를 제공하는 이유는 무엇입니까? (0) | 2020.10.09 |
C # 참조와 포인터의 차이점은 무엇입니까? (0) | 2020.10.09 |
MySQL은 오늘과 같은 날짜 선택 (0) | 2020.10.09 |