NSAttributeString包装问题

web*_*r67 2 objective-c nsattributedstring ios xcode4.6

我正在尝试将属性文本设置为标签.这些属性似乎是一种工作字体和颜色.

我唯一面临的问题是线条的包装.UILabel的大小为(200,300),numberofLines = 0.因此,它应该包裹线,但它不会发生.

   NSMutableString *title=[[NSMutableString alloc] init];
    NSRange range1;
    NSRange range2;
    NSRange range3;



        NSString *str1=@"ABCD EFGHI klm";
        [title appendString:str1];
        range1=NSMakeRange(0, str1.length);


        NSString *str2=@"PQRSSSS ";
        [title appendString:str2];
        range2=NSMakeRange(range1.length, str2.length);


        NSString *str3=@"1235 2347 989034 023490234 90";
        [title appendString:str3];
        range3=NSMakeRange(range2.location+range2.length, str3.length);


    NSMutableAttributedString *attributeText=[[NSMutableAttributedString alloc] initWithString:title];
    [attributeText setAttributes:[NSDictionary dictionaryWithObjectsAndKeys:color1,NSForegroundColorAttributeName,[self getStlylishItalicFont:13.0] ,NSFontAttributeName,nil] range:range1];
    [attributeText setAttributes:[NSDictionary dictionaryWithObjectsAndKeys:color2,NSForegroundColorAttributeName,[self getStylishFont:13.0] ,NSFontAttributeName,nil] range:range2];
    [attributeText setAttributes:[NSDictionary dictionaryWithObjectsAndKeys:color3,NSForegroundColorAttributeName,[self getStylishBoldFont:13.0] ,NSFontAttributeName,nil] range:range3];

    self.myTextLabel.attributedText=attributeText;
Run Code Online (Sandbox Code Playgroud)

UILabel显示如下,即使高度为300.

ABCD EFGHI klm PQRSSSS 1235 234 ...

Joh*_*ijk 5

你需要的是NSParagraphStyle属性:

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
paragraphStyle.alignment = NSTextAlignmentLeft;
paragraphStyle.lineSpacing = 1;

//Now add this to your attributes dictionary for the key NSParagraphStyleAttributeName eg, 
Run Code Online (Sandbox Code Playgroud)

@{NSParagraphStyleAttributeName:paragraphStyle,...}

在一个不相关的说明中,您知道以现代Objective-c格式创建字典会更好.每当我不这样做,我的导师就会生气.这看起来像这样:

[attributeText setAttributes:@{NSForegroundColorAttributeName:color1, NSFontAttributeName:[self getStlylishItalicFont:13.0], NSParagraphStyleAttributeName:paragraphStyle, }];
//The trailing comma in the dictionary definition is not at typo it is important.
Run Code Online (Sandbox Code Playgroud)