iOS 7 sizeWithAttributes:替换sizeWithFont:constrainedToSize


132

如何从新的iOS 7方法sizeWithAttributes返回多行文本CGSize?

我希望这产生与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] }];

此方法仅产生一行文本的高度。



6
+1与我使用相同的字体:)
Lescai Ionel 2014年

Answers:


293

好吧,你可以试试这个:

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];

4
我第一次看到这种表示字典的符号@{...}。这叫什么?
马丁·伯杰

4
兄弟,我几乎对SO失去了信心,然后我来到了这里。
NSPunk 2014年

21
哇。比sizeWithFont:constrainedToSize:不推荐使用的原始方法更加令人讨厌。苹果必须真的讨厌我们。无论如何,+ 1。
aroth 2014年

1
为什么用MAXFLOAT代替CGFLOAT_MAX
朱利安·温纳特

19
迅捷版本:var size = textToMeasure.boundingRectWithSize( CGSizeMake(width, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes:attrs, context:nil).size
mdziadkowiec 2015年

23

这是我的方法:

    // 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];

2
如果长字符串应在行尾断开,则此方法将无效。请参阅elio.d的答案,这是正确的。
朱利安·温纳特

4

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)

3

这是我处理这两种情况的方法,属于一个NSString类别。

- (CGSize) sizeWithFontOrAttributes:(UIFont *) font {
    if (IS_IOS7) {
        NSDictionary *fontWithAttributes = @{NSFontAttributeName:font};
        return [self sizeWithAttributes:fontWithAttributes];
    } else {
        return [self sizeWithFont:font];
    }
}

3

对于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 ()
);

2

如果您具有标签集的文本,字体,numberOfLines和宽度,则此方法将返回标签的大小:

myLabel.numberOfLines = 0;

CGSize size = [myLabel sizeThatFits:CGSizeMake(myLabel.frame.size.width, CGFLOAT_MAX)];`

1

或者,如果您正在查看UITextView,则始终可以使用以下NSLayoutManager方法:

CGSize textSize = [textView.layoutManager usedRectForTextContainer:textView.textContainer].size;

您还可以通过以下方式找到给定字体的行高:

UIFont *font;
CGFloat lineHeight = font.lineHeight;

0

[作为新用户,我不能在@testing的答案上发表评论,而是使他的答案(对于xamarin.ios)更加有用]

我们可以返回一个CGRect,并且只将height参数用于目标UIButton等的gui项。

    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
                                            );

实际上,这本应该在Xamarin.IOS的测试代码中:)希望对任何人都可以帮助:)
Matt

当您有更多代表时,通常会在帖子后添加类似的评论。您还不能执行此操作,因此感谢您提供其他数据,并欢迎您使用Stack Overflow。
Stuart Siegler,2015年

0
CGSize stringsize = [lbl.text sizeWithAttributes:
                         @{NSFontAttributeName:[UIFont fontWithName:FontProximaNovaRegular size:12.0]}];


CGSize adjustedSize = CGSizeMake(ceilf(stringsize.width), ceilf(stringsize.height));

使用ceilf方法妥善管理

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.