사용되지 않는 크기의 대체With Font: iOS 7?
7의 경우 iOS 7의 경우sizeWithFont:을 사용하다 방법 「UIFont」에입니까?sizeWithAttributes:
sizeWithAttributes: 「」, 「」를 합니다.NSDictionary을 지어 UITextAttributeFont글꼴 오브젝트는 다음과 같습니다.
CGRect rawRect = {};
rawRect.size = [string sizeWithAttributes: @{
NSFontAttributeName: [UIFont systemFontOfSize:17.0f],
}];
// Values are fractional -- you should take the ceil to get equivalent values
CGSize adjustedSize = CGRectIntegral(rawRect).size;
은 그 가 폐지되었기 때문에 합니다.NSString+UIKitfunctions)sizewithFont:..., 은 (으)ㄹ 수 있다, 라고 하는 것을 로 한 UIStringDrawing스레드 세이프가 아니었던 도서관입니다. 스레드와 가UIKit을 사용하다특히 여러 스레드에서 동시에 이 기능을 실행하면 앱이 크래시됩니다. 6을 입니다.boundingRectWithSize:...의 for의 NSAttributedString 탑은 이 탑 NSStringDrawing이치노
'새로 온'을 보면NSString boundingRectWithSize:...는 Attribute Array와 으로 Atribute 합니다.NSAttributeString내가 맞혀야 한다면, 이 새로운 것은NSString은 iOS .NSAttributeString.
및 의 iOS7을하겠습니다.NSString sizeWithFont:...NSAttributeString boundingRectWithSize이상한 멀티 스레드 코너 케이스가 있으면 머리가 많이 아플 거예요!.NSString sizeWithFont:constrainedToSize::
종래의 기능:
NSString *text = ...;
CGFloat width = ...;
UIFont *font = ...;
CGSize size = [text sizeWithFont:font
constrainedToSize:(CGSize){width, CGFLOAT_MAX}];
대체 항목:
NSString *text = ...;
CGFloat width = ...;
UIFont *font = ...;
NSAttributedString *attributedText =
[[NSAttributedString alloc] initWithString:text
attributes:@{NSFontAttributeName: font}];
CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
CGSize size = rect.size;
설명서에 기재되어 있는 것에 주의해 주세요.
에서는 이 는 반환되는 7의 합니다.
CGRect뷰 함수를 하여 뷰의 ; 반환된 크기를 사용하여 뷰 크기를 조정하려면 ceil 함수를 사용하여 가장 높은 정수로 값을 올려야 합니다.
따라서 뷰 크기 조정에 사용할 계산된 높이 또는 폭을 끌어내기 위해 다음을 사용합니다.
CGFloat height = ceilf(size.height);
CGFloat width = ceilf(size.width);
Apple Developer 사이트에서 볼 수 있듯이 권장되지 않으므로 를 사용해야 합니다.
#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
NSString *text = @"Hello iOS 7.0";
if (SYSTEM_VERSION_LESS_THAN(@"7.0")) {
// code here for iOS 5.0,6.0 and so on
CGSize fontSize = [text sizeWithFont:[UIFont fontWithName:@"Helvetica"
size:12]];
} else {
// code here for iOS 7.0
CGSize fontSize = [text sizeWithAttributes:
@{NSFontAttributeName:
[UIFont fontWithName:@"Helvetica" size:12]}];
}
이 문제에 대처하기 위해 카테고리를 작성했습니다.다음은 예를 제시하겠습니다.
#import "NSString+StringSizeWithFont.h"
@implementation NSString (StringSizeWithFont)
- (CGSize) sizeWithMyFont:(UIFont *)fontToUse
{
if ([self respondsToSelector:@selector(sizeWithAttributes:)])
{
NSDictionary* attribs = @{NSFontAttributeName:fontToUse};
return ([self sizeWithAttributes:attribs]);
}
return ([self sizeWithFont:fontToUse]);
}
바꾸면 .sizeWithFont:sizeWithMyFont:이제 가도 돼
iOS7에서는 테이블 뷰의 올바른 높이를 반환하기 위한 로직이 필요했습니다.heightForRowAtIndexPath 메서드, 그러나 크기WithAttributes는 고정 너비 테이블셀에 넣을지 모르기 때문에 문자열 길이에 관계없이 항상 같은 높이를 반환합니다.이것은 나에게 매우 적합하고, 테이블 셀의 폭을 고려하여 정확한 높이를 계산한다!이것은 위의 Mr.T의 답변을 바탕으로 하고 있습니다.
NSString *text = @"The text that I want to wrap in a table cell."
CGFloat width = tableView.frame.size.width - 15 - 30 - 15; //tableView width - left border width - accessory indicator - right border width
UIFont *font = [UIFont systemFontOfSize:17];
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName: font}];
CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
CGSize size = rect.size;
size.height = ceilf(size.height);
size.width = ceilf(size.width);
return size.height + 15; //Add a little more padding for big thumbs and the detailText label
동적 높이를 사용하는 여러 줄 레이블의 경우 크기를 올바르게 설정하려면 추가 정보가 필요할 수 있습니다.사이즈 사용 가능글꼴과 줄 바꿈 모드를 모두 지정하려면 UIFont 및 NSParaph Style을 사용하는 WithAttributes를 사용합니다.
문단 유형을 정의하고 다음과 같은 NSDictionary를 사용합니다.
// set paragraph style
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[style setLineBreakMode:NSLineBreakByWordWrapping];
// make dictionary of attributes with paragraph style
NSDictionary *sizeAttributes = @{NSFontAttributeName:myLabel.font, NSParagraphStyleAttributeName: style};
// get the CGSize
CGSize adjustedSize = CGSizeMake(label.frame.size.width, CGFLOAT_MAX);
// alternatively you can also get a CGRect to determine height
CGRect rect = [myLabel.text boundingRectWithSize:adjustedSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:sizeAttributes
context:nil];
높이를 찾고 있는 경우 CGSize 'adjusted Size' 또는 CGRect를 rect.size.height 속성으로 사용할 수 있습니다.
NSParagraph Style에 대한 자세한 내용은 https://developer.apple.com/library/mac/documentation/cocoa/reference/applicationkit/classes/NSParagraphStyle_Class/Reference/Reference.html를 참조하십시오.
// max size constraint
CGSize maximumLabelSize = CGSizeMake(184, FLT_MAX)
// font
UIFont *font = [UIFont fontWithName:TRADE_GOTHIC_REGULAR size:20.0f];
// set paragraph style
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
// dictionary of attributes
NSDictionary *attributes = @{NSFontAttributeName:font,
NSParagraphStyleAttributeName: paragraphStyle.copy};
CGRect textRect = [string boundingRectWithSize: maximumLabelSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
CGSize expectedLabelSize = CGSizeMake(ceil(textRect.size.width), ceil(textRect.size.height));
UILabel 인스턴스를 사용하는 함수를 만듭니다.CGSize를 반환한다.
CGSize constraint = CGSizeMake(label.frame.size.width , 2000.0);
// Adjust according to requirement
CGSize size;
if([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0){
NSRange range = NSMakeRange(0, [label.attributedText length]);
NSDictionary *attributes = [label.attributedText attributesAtIndex:0 effectiveRange:&range];
CGSize boundingBox = [label.text boundingRectWithSize:constraint options: NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));
}
else{
size = [label.text sizeWithFont:label.font constrainedToSize:constraint lineBreakMode:label.lineBreakMode];
}
return size;
대체 솔루션-
CGSize expectedLabelSize;
if ([subTitle respondsToSelector:@selector(sizeWithAttributes:)])
{
expectedLabelSize = [subTitle sizeWithAttributes:@{NSFontAttributeName:subTitleLabel.font}];
}else{
expectedLabelSize = [subTitle sizeWithFont:subTitleLabel.font constrainedToSize:subTitleLabel.frame.size lineBreakMode:NSLineBreakByWordWrapping];
}
@bitsand를 기반으로 하는 이 새로운 메서드는 NSString+에 추가되었습니다.기타 카테고리:
- (CGRect) boundingRectWithFont:(UIFont *) font constrainedToSize:(CGSize) constraintSize lineBreakMode:(NSLineBreakMode) lineBreakMode;
{
// set paragraph style
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[style setLineBreakMode:lineBreakMode];
// make dictionary of attributes with paragraph style
NSDictionary *sizeAttributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName: style};
CGRect frame = [self boundingRectWithSize:constraintSize options:NSStringDrawingUsesLineFragmentOrigin attributes:sizeAttributes context:nil];
/*
// OLD
CGSize stringSize = [self sizeWithFont:font
constrainedToSize:constraintSize
lineBreakMode:lineBreakMode];
// OLD
*/
return frame;
}
결과 프레임의 크기만 사용합니다.
쓸 수 요.sizeWithFont7.0 및 또는 라인이 \n.
사용하기 전에 텍스트 트리밍
label.text = [label.text stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
것도 일 수 있어요.sizeWithAttributes ★★★★★★★★★★★★★★★★★」[label sizeToFit].
또, 당신이 시간이 날 때마다nsstringdrawingtextstorage message sent to deallocated instanceiOS 7.0 i i 、 i i i i i i i i 。
자동 치수 사용(스위프트):
tableView.estimatedRowHeight = 68.0
tableView.rowHeight = UITableViewAutomaticDimension
NB: 1. UITableViewCell 프로토타입을 적절하게 설계해야 합니다(예: set UILabel.numberOfLines = 0 등). 2.높이 ForRowAt 제거IndexPath 메서드

비디오: https://youtu.be/Sz3XfCsSb6k
boundingRectWithSize:options:attributes:context:
Xamarin에서 허용되는 답변은 다음과 같습니다(사용 크기).With Attributes 및 UIText Attribute Font):
UIStringAttributes attributes = new UIStringAttributes
{
Font = UIFont.SystemFontOfSize(17)
};
var size = text.GetSizeUsingAttributes(attributes);
@Ayush 답변:
Apple Developer 사이트에서 볼 수 있듯이 권장되지 않으므로 를 사용해야 합니다.
음, 2019+에 Swift와String 및 Objective-c NSString 해서 a의 하게 알 수 방법은 다음과 String'이것'은 다음과 같습니다.
let stringSize = NSString(string: label.text!).size(withAttributes: [.font : UIFont(name: "OpenSans-Regular", size: 15)!])
- (CGSize) sizeWithMyFont:(UIFont *)fontToUse
{
if ([self respondsToSelector:@selector(sizeWithAttributes:)])
{
NSDictionary* attribs = @{NSFontAttributeName:fontToUse};
return ([self sizeWithAttributes:attribs]);
}
return ([self sizeWithFont:fontToUse]);
}
필요한 경우 다음과 같은 모노터치를 제공합니다.
/// <summary>
/// Measures the height of the string for the given width.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="font">The font.</param>
/// <param name="width">The width.</param>
/// <param name="padding">The padding.</param>
/// <returns></returns>
public static float MeasureStringHeightForWidth(this string text, UIFont font, float width, float padding = 20)
{
NSAttributedString attributedString = new NSAttributedString(text, new UIStringAttributes() { Font = font });
RectangleF rect = attributedString.GetBoundingRect(new SizeF(width, float.MaxValue), NSStringDrawingOptions.UsesLineFragmentOrigin, null);
return rect.Height + padding;
}
다음과 같이 사용할 수 있습니다.
public override float GetHeightForRow(UITableView tableView, NSIndexPath indexPath)
{
//Elements is a string array
return Elements[indexPath.Row].MeasureStringHeightForWidth(UIFont.SystemFontOfSize(UIFont.LabelFontSize), tableView.Frame.Size.Width - 15 - 30 - 15);
}
CGSize maximumLabelSize = CGSizeMake(label.frame.size.width, FLT_MAX);
CGSize expectedLabelSize = [label sizeThatFits:maximumLabelSize];
float heightUse = expectedLabelSize.height;
다음 구문을 사용해 보십시오.
NSAttributedString *attributedText =
[[NSAttributedString alloc] initWithString:text
attributes:@{NSFontAttributeName: font}];
IOS 7에서는 이 모든 것이 통하지 않았습니다.이게 제가 결국 하게 된 일입니다.이것을 커스텀 셀 클래스에 넣고, my highForCellAtIndexPath 메서드를 호출합니다.
앱스토어에서 앱을 볼 때 내 셀은 설명 셀과 비슷합니다.
스토리보드에서 라벨을 '속성'으로 설정합니다.Text'에서 줄 수를 0으로 설정하고(ios 6+만 해당), 줄 수를 워드랩으로 설정합니다.
그런 다음 커스텀 셀클래스의 셀 콘텐츠 높이를 모두 합산합니다.이 경우 상단에 항상 "Description"(_description)이라고 하는 라벨이 있습니다.Heading Label), 실제 설명(_description Label)을 포함하는 크기가 가변적인 작은 라벨. 셀의 선두에서 제목(_description)까지의 제약 조건(_description(_description)Heading Label Top Constraint).아래쪽에 조금 띄어쓰기에 3을 추가했습니다(부제 타입의 셀에 애플이 배치하는 양과 거의 같음).
- (CGFloat)calculateHeight
{
CGFloat width = _descriptionLabel.frame.size.width;
NSAttributedString *attributedText = _descriptionLabel.attributedText;
CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX} options: NSStringDrawingUsesLineFragmentOrigin context:nil];
return rect.size.height + _descriptionHeadingLabel.frame.size.height + _descriptionHeadingLabelTopConstraint.constant + 3;
}
내 Table View 대리인:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
if (indexPath.row == 0) {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"descriptionCell"];
DescriptionCell *descriptionCell = (DescriptionCell *)cell;
NSString *text = [_event objectForKey:@"description"];
descriptionCell.descriptionLabel.text = text;
return [descriptionCell calculateHeight];
}
return 44.0f;
}
if 문을 조금 더 '간단'하게 변경하여 실제로 데이터 원본에서 셀 식별자를 얻을 수 있습니다.제 경우 셀의 양이 정해진 순서대로 있기 때문에 셀은 하드 코드화 됩니다.
언급URL : https://stackoverflow.com/questions/18897896/replacement-for-deprecated-sizewithfont-in-ios-7
'source' 카테고리의 다른 글
| Git에서 특정 커밋을 병합하는 방법 (0) | 2023.04.17 |
|---|---|
| 비트맵 이미지의 특정 픽셀 색상 찾기 (0) | 2023.04.17 |
| 삽입 명령 실행 및 SQL에 삽입된 ID 반환 (0) | 2023.04.17 |
| 아이폰 네비게이션바 제목 텍스트 색상 (0) | 2023.04.17 |
| [NSObject description]의 Swift는 무엇입니까? (0) | 2023.04.17 |