Подтвердить что ты не робот

Как получить ширину NSString?

Я пытаюсь получить ширину NSString (например, NSString * myString = @ "hello" ). Есть ли способ сделать это?

Спасибо.

4b9b3361

Ответ 1

Здесь относительно простой подход. Просто создайте NSAttributedString с соответствующим шрифтом и спросите его размер:

- (CGFloat)widthOfString:(NSString *)string withFont:(NSFont *)font {
     NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
     return [[[NSAttributedString alloc] initWithString:string attributes:attributes] size].width;
 }

Ответ 2

UIFont * font = [UIFont systemFontOfSize:15];

CGSize stringSize = [aString sizeWithFont:font]; 

CGFloat width = stringSize.width;

Ответ 3

Отправьте строку a sizeWithAttributes: сообщение, передав словарь, содержащий атрибуты, с помощью которых вы хотите измерить строку.

Ответ 4

Я не знаю, предположите ли вы использовать это в cocoa touch. если это так, то:

- (CGFloat)widthOfString:(NSString *)string withFont:(NSFont *)font {
     NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
     return [[[NSAttributedString alloc] initWithString:string attributes:attributes] size].width;
 }

не работает.

в cocoa touch, вы должны добавить структуру coretext и импортировать заголовок и напишите свой код следующим образом:

UIFont *font = [UIFont fontWithName:@"HelveticaNeue-BoldItalic" size:DEFAULT_FONT_SIZE];
//    NSLog(@"%@", NSFontAttributeName);
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, (NSString     *)kCTFontAttributeName, nil];

но, GEE!!!!!

NSMutableAttributedString *as = [[NSMutableAttributedString alloc] initWithString:self.caption attributes:attributes];
[as size].width;

нет такого метода в NSMutableAttributedString!

наконец, это сработало бы

[self.caption sizeWithFont:font].width

Ответ 5

как для ios 7, и это правильный путь:

NSString * buttonTitle = @"demo title";
CGSize stringSize = [buttonTitle sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:17.0f]}];

Ответ 6

Здесь решение Стивена в Clozure Common Lisp при использовании моста Objective C. Я столкнулся с этим сообщением при поиске решения, и я просто переписал версию Стивена, которая отлично работала для меня. Другие, использующие Clozure, могут найти это полезным:

(defun string-width (str font)
  (let* ((dict (#/dictionaryWithObjectsAndKeys: ns:ns-mutable-dictionary
                font #$NSFontAttributeName
                ccl:+null-ptr+))
         (attr (#/initWithString:attributes: (#/alloc ns:ns-attributed-string)
                (ccl::%make-nsstring str)
                dict))
         (size (#/size attr)))
    (ns:ns-size-width size)))

Ответ 7

Использование строки, присвоенной UILabel:

- (CGSize)getStringSizeWithText:(NSString *)string font:(UIFont *)font{

    UILabel *label = [[UILabel alloc] init];
    label.text = string;
    label.font = font;

    return label.attributedText.size;
}

Ответ 8

Извините, мой вопрос не был достаточно подробным и не совсем то, что я пытаюсь сделать. Я использую текстовое хранилище, менеджер макетов и текстовый контейнер. Решение состоит в том, чтобы использовать диспетчер компоновки для определения прямоугольника, который ограничивает прямоугольник. Вот код.

NSTextStorage *textStorage = [[NSTextStorage alloc] initWithString:@"hello"];
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
NSTextContainer *textContainer = [[NSTextContainer alloc] init];

[layoutManager addTextContainer:textContainer];
[textContainer release];

[textStorage addLayoutManager:layoutManager];
[layoutManager release];

//Figure out the bounding rectangle
NSRect stringRect = [layoutManager boundingRectForGlyphRange:NSMakeRange(0, [layoutManager numberOfGlyphs]) inTextContainer:textContainer];

Ответ 9

UIKit имеет приятное дополнение к NSString, делая sizeWithAttributes: немного легче:

CGSize titleSize = [title sizeWithFont:titleFont 
                     constrainedToSize:contentCellSize 
                         lineBreakMode:UILineBreakModeWordWrap];

Ответ 10

На всякий случай вам интересно, как проверить размер метки, вы должны использовать UIFont, а не NSFont (даже не уверен, что существует)