【问题标题】:How to change properties of particular text in a label如何更改标签中特定文本的属性
【发布时间】:2015-12-26 03:22:29
【问题描述】:

我有一个标签,我以编程方式设置了标签的文本。我想将其中一个单词设置为粗体,其余的正常。但是,我无法控制文本的属性。例如,我想要这个“这是一个示例”,但我只能实现这个“这是一个示例”。

【问题讨论】:

    标签: ios xcode text label


    【解决方案1】:

    试试这个:

        NSString *text = @"This is an example";
        NSString *textBold = @"example";
    
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
        [attributedString beginEditing];
        [attributedString addAttribute:NSFontAttributeName
                                 value:[UIFont boldSystemFontOfSize:20.0f]
                                 range:[text rangeOfString:textBold]];
    
        [attributedString endEditing];
        [labelObj setAttributedText:attributedString];
    

    【讨论】:

      【解决方案2】:

      查看标签的attributedText 属性。它允许您使用NSAttributedString 指定样式文本。解释如何构建 NSAttributedString 超出了 SO 答案的范围,但您应该能够在 Xcode 帮助系统和在线找到充足的信息。

      【讨论】:

        【解决方案3】:

        让我给你看一个有关属性文本的演示。

         NSDictionary*subStrAttribute1 = @{  
         NSForegroundColorAttributeName: [UIColor redColor],  
         NSStrikethroughStyleAttributeName:@2  
         };  
        
         NSDictionary *subStrAttribute2 =@{  
         NSForegroundColorAttributeName: [UIColor greenColor]  
        };  
        
        NSString *strDisplayText3 =@"Red and Green";  
        NSMutableAttributedString *attributedText3 = [[NSMutableAttributedString alloc] initWithString:strDisplayText3];  
        [attributedText3 setAttributes:subStrAttribute1 range:NSMakeRange(0,3)];  
        [attributedText3 setAttributes:subStrAttribute2 range:NSMakeRange(8,5)];  
        self.lblInfo3.attributedText= attributedText3;  
        

        【讨论】:

          【解决方案4】:

          由于ios6 uilabel 支持属性字符串,所以可以使用。 对于您的特定情况,以下代码将起作用-

          NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"This is an example"];
          
          [string addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:20.0] range:NSMakeRange(11, 7)];
          
          label.attributedText = string;
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-05-16
            • 2016-09-13
            • 2017-09-20
            • 1970-01-01
            • 2023-03-26
            • 1970-01-01
            • 2016-01-22
            • 1970-01-01
            相关资源
            最近更新 更多