对 NSAttributedstring 的不同部分应用不同的属性

发布于 2024-12-21 17:56:04 字数 242 浏览 1 评论 0 原文

我知道可以将属性应用于 NSAttributedString。

但是我们如何将不同的属性应用于相同的属性字符串。

对于字符串“这是一个属性文本”。

我们如何将特定属性(背景颜色或前景色)设置为“This is” 另一个属性(背景颜色或前景色)到“属性文本”。

有什么办法可以实现这一点吗......?

还有什么方法可以在 iOS 中设置 NSAttributedString 的背景颜色吗?

I know it is possible to apply attributes to an NSAttributedString.

But how can we apply different attributes to same attributed string.

for the string "This is an attributed text."

How can we set a particular attribute(background color or foreground color) to "This is"
another attribute(background color or foreground color) to "an attributed text."

Is there any way to achieve this....?

Also is there any way to set the background color of an NSAttributedString in iOS?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

橪书 2024-12-28 17:56:04

制作属性字符串的可变副本,然后使用:

-setAttributes:range:
-addAttributes:范围:
-addAttribute:值:范围:
-removeAttributes:range:

例如,为前四个字母设置红色:

NSMutableAttributedString *mutAttrStr = [attributedString mutableCopy];
CGColorRef redClr = [UIColor redColor].CGColor;
NSDictionary *newAttributes = [NSDictionary dictionaryWithObject:(id)redClr forKey:(id)kCTForegroundColorAttributeName];
[mutAttrStr addAttributes:newAttributes range:NSMakeRange(0, 4)];

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableAttributedString_Class/Reference/Reference.html

没有内置的绘制方法iOS 上的背景颜色。您可以为该属性创建一个自定义字符串常量,例如“MyBackgroundColorAttributeName”,然后您必须自己绘制它。

Make a mutable copy of the attributed string, and then use either:

-setAttributes:range:
-addAttributes:range:
-addAttribute:value:range:
-removeAttributes:range:

for example, to set a red color for the first four letters:

NSMutableAttributedString *mutAttrStr = [attributedString mutableCopy];
CGColorRef redClr = [UIColor redColor].CGColor;
NSDictionary *newAttributes = [NSDictionary dictionaryWithObject:(id)redClr forKey:(id)kCTForegroundColorAttributeName];
[mutAttrStr addAttributes:newAttributes range:NSMakeRange(0, 4)];

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableAttributedString_Class/Reference/Reference.html

There's no built-in way to draw the background color on iOS. You can create a custom string constant for the attribute, eg "MyBackgroundColorAttributeName", and then you'll have to draw it yourself.

装纯掩盖桑 2024-12-28 17:56:04

我正在使用以下扩展来更改“NSMutableAttributedString”颜色,它很好地实现了这一点。它可以用作模板

extension NSMutableAttributedString {

    func changeColourOf(_ terms: [String], toThisColour termsColour:  UIColor, 
                        andForegroundColour fontColour: UIColor) {

        // Set your foreground Here
        addAttributes([NSAttributedString.Key.foregroundColor : fontColour], 
                      range: NSMakeRange(0, self.length))

        // Convert "NSMutableAttributedString" to a NSString  
        let string = self.string as NSString
    
        // Create a for loop for ther terms array
        for term in terms {
            // This will be the range of each term
            let underlineRange = string.range(of: term)
      
            // Finally change the term colour
            addAttribute(NSAttributedString.Key.foregroundColor, 
                         value: termsColour, 
                         range: underlineRange)
        }
    }
}

示例:

let someMutableStr = NSMutableAttributedString(string: "Hello World 2017 !")
someMutableStr.changeColourOf(["Hello", "2017"], 
                              toThisColour: .blue, 
                              theStringFontColour: .red)

编辑 2021

 extension NSMutableAttributedString
 {
    func colourTerms(_ terms:[String] = [],
                     withColour colour:UIColor = .blue,
                     onforegroundColour foregroundColour:UIColor = .white)
{
    let fontSize:CGFloat = 25
      self.addAttributes([NSAttributedString.Key.font:UIFont.systemFont(ofSize: fontSize),NSAttributedString.Key.foregroundColor:foregroundColour], range:NSMakeRange(0, self.length) )
    let text = self.string
    for term in terms
    {
        let charCount = term.count
        var options:NSString.EnumerationOptions = .byWords
        switch charCount
        {
            case 1:
                options = .byComposedCharacterSequences
            default:
                if term.contains(" ")
                {
                    options = .bySentences
                }else
                {
                    options = .byWords
                }
        }
        string.enumerateSubstrings(in: text.startIndex..<text.endIndex, 
          options: options)
       { (subString,substringRange,_,_) in
            if subString!.contains(term)
            {
                 self.addAttribute(NSAttributedString.Key.foregroundColor,
              value: colour, 
              range: NSRange(substringRange, in: text))}}}}}

示例 2021

    let attrText = NSMutableAttributedString(string: """
    Hello World 2021!
    Happy 2021 
    """)
    attrText.colourTerms(["Hello","2021"])

    //Before this second color will stay the same , now fixed!
    //See images below

在此处输入图像描述 示例 2017

问题在这里
这是问题所在
输入图片此处描述
现在

I am using the following extension to change "NSMutableAttributedString" colour and it did the trick nicely. It can be used as a template

extension NSMutableAttributedString {

    func changeColourOf(_ terms: [String], toThisColour termsColour:  UIColor, 
                        andForegroundColour fontColour: UIColor) {

        // Set your foreground Here
        addAttributes([NSAttributedString.Key.foregroundColor : fontColour], 
                      range: NSMakeRange(0, self.length))

        // Convert "NSMutableAttributedString" to a NSString  
        let string = self.string as NSString
    
        // Create a for loop for ther terms array
        for term in terms {
            // This will be the range of each term
            let underlineRange = string.range(of: term)
      
            // Finally change the term colour
            addAttribute(NSAttributedString.Key.foregroundColor, 
                         value: termsColour, 
                         range: underlineRange)
        }
    }
}

Example:

let someMutableStr = NSMutableAttributedString(string: "Hello World 2017 !")
someMutableStr.changeColourOf(["Hello", "2017"], 
                              toThisColour: .blue, 
                              theStringFontColour: .red)

Edit 2021

 extension NSMutableAttributedString
 {
    func colourTerms(_ terms:[String] = [],
                     withColour colour:UIColor = .blue,
                     onforegroundColour foregroundColour:UIColor = .white)
{
    let fontSize:CGFloat = 25
      self.addAttributes([NSAttributedString.Key.font:UIFont.systemFont(ofSize: fontSize),NSAttributedString.Key.foregroundColor:foregroundColour], range:NSMakeRange(0, self.length) )
    let text = self.string
    for term in terms
    {
        let charCount = term.count
        var options:NSString.EnumerationOptions = .byWords
        switch charCount
        {
            case 1:
                options = .byComposedCharacterSequences
            default:
                if term.contains(" ")
                {
                    options = .bySentences
                }else
                {
                    options = .byWords
                }
        }
        string.enumerateSubstrings(in: text.startIndex..<text.endIndex, 
          options: options)
       { (subString,substringRange,_,_) in
            if subString!.contains(term)
            {
                 self.addAttribute(NSAttributedString.Key.foregroundColor,
              value: colour, 
              range: NSRange(substringRange, in: text))}}}}}

Example 2021

    let attrText = NSMutableAttributedString(string: """
    Hello World 2021!
    Happy 2021 
    """)
    attrText.colourTerms(["Hello","2021"])

    //Before this second color will stay the same , now fixed!
    //See images below

enter image description here Example 2017

Here is the problem
Here is the problem
enter image description here
Now

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文