Я пытаюсь получить ширину NSString (например, NSString * myString = @ "hello" ). Есть ли способ сделать это?
Спасибо.
Я пытаюсь получить ширину NSString (например, NSString * myString = @ "hello" ). Есть ли способ сделать это?
Спасибо.
Здесь относительно простой подход. Просто создайте NSAttributedString с соответствующим шрифтом и спросите его размер:
- (CGFloat)widthOfString:(NSString *)string withFont:(NSFont *)font {
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
return [[[NSAttributedString alloc] initWithString:string attributes:attributes] size].width;
}
UIFont * font = [UIFont systemFontOfSize:15];
CGSize stringSize = [aString sizeWithFont:font];
CGFloat width = stringSize.width;
Отправьте строку a sizeWithAttributes:
сообщение, передав словарь, содержащий атрибуты, с помощью которых вы хотите измерить строку.
Я не знаю, предположите ли вы использовать это в 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
как для ios 7, и это правильный путь:
NSString * buttonTitle = @"demo title";
CGSize stringSize = [buttonTitle sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:17.0f]}];
Здесь решение Стивена в 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)))
Использование строки, присвоенной UILabel:
- (CGSize)getStringSizeWithText:(NSString *)string font:(UIFont *)font{
UILabel *label = [[UILabel alloc] init];
label.text = string;
label.font = font;
return label.attributedText.size;
}
Извините, мой вопрос не был достаточно подробным и не совсем то, что я пытаюсь сделать. Я использую текстовое хранилище, менеджер макетов и текстовый контейнер. Решение состоит в том, чтобы использовать диспетчер компоновки для определения прямоугольника, который ограничивает прямоугольник. Вот код.
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];
UIKit имеет приятное дополнение к NSString, делая sizeWithAttributes: немного легче:
CGSize titleSize = [title sizeWithFont:titleFont
constrainedToSize:contentCellSize
lineBreakMode:UILineBreakModeWordWrap];
На всякий случай вам интересно, как проверить размер метки, вы должны использовать UIFont, а не NSFont (даже не уверен, что существует)