IOS 7 sizeWithAttributes: замена для sizeWithFont: constrainedToSize
Как вы возвращаете многострочный текст CGSize из нового размера метода iOS 7 с атрибутами?
Я хотел бы, чтобы это производило те же результаты, что и sizeWithFont: constrainedToSize.
NSString *text = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu urna quis lacus imperdiet scelerisque a nec neque. Mauris eget feugiat augue, vitae porttitor mi. Curabitur vitae sollicitudin augue. Donec id sapien eros. Proin consequat tellus in vehicula sagittis. Morbi sed felis a nibh hendrerit hendrerit. Lorem ipsum dolor sit."
CGSize textSize = [text sizeWithAttributes:@{ NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Light" size:16.0] }];
Этот метод создает только высоту для одной строки текста.
Ответы
Ответ 1
Хорошо, вы можете попробовать следующее:
NSDictionary *attributes = @{NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:14]};
// NSString class method: boundingRectWithSize:options:attributes:context is
// available only on ios7.0 sdk.
CGRect rect = [textToMeasure boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
Ответ 2
Вот как я это сделал:
// Get a font to draw it in
UIFont *font = [UIFont boldSystemFontOfSize: 28];
CGRect textRect;
NSDictionary *attributes = @{NSFontAttributeName: font};
// How big is this string when drawn in this font?
textRect.size = [text sizeWithAttributes:attributes];
// Draw the string
[text drawInRect:textRect withAttributes:attributes];
Ответ 3
Здесь мой метод решения обеих ситуаций относится к категории NSString
.
- (CGSize) sizeWithFontOrAttributes:(UIFont *) font {
if (IS_IOS7) {
NSDictionary *fontWithAttributes = @{NSFontAttributeName:font};
return [self sizeWithAttributes:fontWithAttributes];
} else {
return [self sizeWithFont:font];
}
}
Ответ 4
Для Xamarin.iOS:
UIFont descriptionLabelFont = UIFont.SystemFontOfSize (11);
NSString textToMeasure = (NSString)DescriptionLabel.Text;
CGRect labelRect = textToMeasure.GetBoundingRect (
new CGSize(this.Frame.Width, nfloat.MaxValue),
NSStringDrawingOptions.UsesLineFragmentOrigin,
new UIStringAttributes () { Font = descriptionLabelFont },
new NSStringDrawingContext ()
);
Ответ 5
Swift 2.3:
let attributes = [NSFontAttributeName:UIFont(name: "HelveticaNeue", size: 14)]
let rect = NSString(string: textToMeasure).boundingRectWithSize(
CGSizeMake(width, CGFLOAT_MAX),
options: NSStringDrawingOptions.UsesLineFragmentOrigin,
attributes: attributes, context: nil)
Свифт 4:
let attributes = [NSFontAttributeName:UIFont(name: "HelveticaNeue", size: 14)]
let rect = NSString(string: textToMeasure).boundingRect(
with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude),
options: NSStringDrawingOptions.usesLineFragmentOrigin,
attributes: attributes as [NSAttributedString.Key : Any], context: nil)
Ответ 6
Если у вас есть текст, шрифт, numberOfLines и ширина вашего набора меток, этот метод возвращает размер вашей метки:
myLabel.numberOfLines = 0;
CGSize size = [myLabel sizeThatFits:CGSizeMake(myLabel.frame.size.width, CGFLOAT_MAX)];`
Ответ 7
В качестве альтернативы, если вы смотрите на UITextView
, вы всегда можете использовать метод NSLayoutManager
:
CGSize textSize = [textView.layoutManager usedRectForTextContainer:textView.textContainer].size;
Вы также можете найти высоту строки для заданного шрифта:
UIFont *font;
CGFloat lineHeight = font.lineHeight;
Ответ 8
[Как новый пользователь, я не могу опубликовать комментарий к @testing answer, но сделать его ответ (для xamarin.ios) более полезным]
Мы можем вернуть CGRect и использовать только параметр высоты для элемента gui, на который мы нацеливаем UIButton etc.Passing в любых параметрах, которые нам нужны ниже
public CGRect GetRectForString(String strMeasure, int fontSize, nfloat guiItemWidth)
{
UIFont descriptionLabelFont = UIFont.SystemFontOfSize (fontSize);
NSString textToMeasure = (NSString)strMeasure;
CGRect labelRect = textToMeasure.GetBoundingRect (
new CGSize(guiItemWidth, nfloat.MaxValue),
NSStringDrawingOptions.UsesLineFragmentOrigin,
new UIStringAttributes () { Font = descriptionLabelFont },
new NSStringDrawingContext ()
);
return labelRect;
}
header_Revision.Frame = new CGRect (5
, verticalAdjust
, View.Frame.Width-10
, GetRectForString( header_Revision.Title(UIControlState.Normal)
, 18
, View.Frame.Width-10 ).Height
);
Ответ 9
CGSize stringsize = [lbl.text sizeWithAttributes:
@{NSFontAttributeName:[UIFont fontWithName:FontProximaNovaRegular size:12.0]}];
CGSize adjustedSize = CGSizeMake(ceilf(stringsize.width), ceilf(stringsize.height));
использовать ceilf
метод для управления надлежащим образом