iOS 7 sizeWithAttributes: sizeWithFont için değiştirme: constrainedToSize


132

Yeni iOS 7 yönteminden sizeWithAttributes'dan çok satırlı bir metin CGSize nasıl döndürülür?

Bunun sizeWithFont: constrainedToSize ile aynı sonuçları vermesini istiyorum.

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

Bu yöntem yalnızca tek bir metin satırı için yükseklik üretir.



6
Benimle aynı yazı tipine sahip olduğum için +1 :)
Lescai Ionel

Yanıtlar:


293

peki şunu deneyebilirsiniz:

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
İlk defa sözlükler için bu gösterimi görüyorum @{...}. Adı ne?
Martin Berger

4
Kardeşim, neredeyse SO'ya olan inancımı kaybediyordum, sonra buraya geldim.
NSPunk

21
Vay. Kullanımdan sizeWithFont:constrainedToSize:kaldırılan orijinal yöntemden çok daha geniş . Apple bizden gerçekten nefret ediyor olmalı. Her durumda +1.
2014

1
MAXFLOATBunun yerine neden kullanıyorsun CGFLOAT_MAX?
Julian F.Weinert

19
Hızlı versiyon:var size = textToMeasure.boundingRectWithSize( CGSizeMake(width, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes:attrs, context:nil).size
mdziadkowiec

23

Ben böyle yaptım:

    // 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
Uzun bir dizge satırın sonunda kırılırsa bu işe yaramaz. Elio.d'nin doğru olan cevabına bakın.
Julian F.Weinert

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)

Swift 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

İşte her iki durumla başa çıkma yöntemim, bir NSStringkategoriye giriyor .

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

3

Xamarin.iOS için:

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

Etiket ayarınızın metni, yazı tipi, numberOfLines ve genişliğine sahipseniz, bu yöntem etiketinizin boyutunu döndürür:

myLabel.numberOfLines = 0;

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

1

Alternatif olarak, bakıyorsanız, UITextViewher zaman NSLayoutManageryöntemi kullanabilirsiniz :

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

Belirli bir yazı tipi için satır yüksekliğini şu şekilde de bulabilirsiniz:

UIFont *font;
CGFloat lineHeight = font.lineHeight;

0

[Yeni bir kullanıcı olarak, @ testinin cevabına yorum gönderemem, ancak cevabını (xamarin.ios için) daha yararlı kılmak için]

Bir CGRect döndürebiliriz ve sadece UIButton vb. Hedeflediğimiz gui öğesi için height parametresini kullanabiliriz.

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

Bunun aslında Xamarin.IOS için test edilen güzel kodunun altında olması gerekiyordu :) Umarım herkese yardımcı olur :)
Matt

Daha fazla temsilciniz olduğunda, bunun gibi bir yorum genellikle gönderiye eklenir. Henüz bunu yapamazsınız, bu nedenle ek veriler için teşekkürler ve Stack Overflow'a hoş geldiniz.
Stuart Siegler

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


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

ceilfdüzgün yönetmek için yöntem kullanın

Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.