使用属性“firstLineHeadIndent”的attributionString在UILabel中无法正确显示

时间:2017-04-20 05:00:47

标签: ios objective-c uilabel nsattributedstring

我正在尝试在UILabel中显示一个attributionString,并在其属性中添加了“firstLineHeadIndent”属性。

有16个字符的“国”,它应分成两行。但是UILabel只在一行中显示了14个字符,如图所示“16个字符不正确”。

当使用17个字符时它可以正确显示。任何人都可以告诉我为什么? 这是我的代码:

  - (void)viewDidLoad {
    [super viewDidLoad];

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 300, 80)];
    label.numberOfLines = 0;
    label.lineBreakMode = NSLineBreakByWordWrapping;
    [self.view addSubview: label];

    NSMutableParagraphStyle *paraStyle = [NSMutableParagraphStyle new];
    paraStyle.firstLineHeadIndent = 40;
    paraStyle.lineBreakMode = NSLineBreakByWordWrapping;
    NSDictionary *attrs = @{
                            NSParagraphStyleAttributeName:paraStyle,
                            NSFontAttributeName:[UIFont systemFontOfSize:17 weight:UIFontWeightBold],
                            NSKernAttributeName:@.9f
                            };
    label.attributedText = [[NSAttributedString alloc] initWithString:@"国国国国国国国国国国国国国国国国" attributes:attrs];}

16个字符不正确:

not correct with 16 characters

正确显示17个字符:

show correctly with 17 characters

3 个答案:

答案 0 :(得分:0)

enter image description here 更新了答案

更改此行:至

   UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 300, 80)];
    label.numberOfLines = 0;
    label.lineBreakMode = NSLineBreakByCharWrapping;
    label.adjustsFontSizeToFitWidth=YES;
    label.backgroundColor=[UIColor redColor];
    label.textAlignment=NSTextAlignmentLeft;
    [self.view addSubview: label];

    NSMutableParagraphStyle *paraStyle = [NSMutableParagraphStyle new];
    paraStyle.firstLineHeadIndent = 20;
    paraStyle.lineBreakMode = NSLineBreakByWordWrapping;
    NSDictionary *attrs = @{
                            NSParagraphStyleAttributeName:paraStyle,
                            NSFontAttributeName:[UIFont systemFontOfSize:16 weight:UIFontWeightBold],
                            NSKernAttributeName:@.9f
                            };
    label.attributedText = [[NSAttributedString alloc] initWithString:@"国国国国国国国国国国国国国国国国" attributes:attrs];

解决方案2:

删除段落:事物

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 300, 80)];
    label.numberOfLines = 0;

 label.text=@"国国国国国国国国国国国国国国国国国国";
    label.lineBreakMode = NSLineBreakByWordWrapping;
    label.adjustsFontSizeToFitWidth=YES;
    label.backgroundColor=[UIColor redColor];
    label.textAlignment=NSTextAlignmentCenter;
    [self.view addSubview: label];

答案 1 :(得分:0)

我也遇到了这个问题,我认为这是UILabel的错误。因此,我尝试将其更改为UITextView,并成功了。

答案 2 :(得分:0)

我认为您可以将NSTextAttachment与透明图像配合使用以增加空间。