【问题标题】:Specifed color changing in string. Swift iOS字符串中指定的颜色变化。斯威夫特 iOS
【发布时间】:2016-11-17 19:33:59
【问题描述】:

我想知道如何制作彩色绳子。

我的意思是:

我需要字符串例如

FirstLetter - 白色,第二个 - 蓝色,第三个 - 红色,第四个 - 橙色,第五个 - 白色,依此类推。

我用谷歌搜索了这行代码:

myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:2,length:4))

但是它得到了位置和长度,但是如何按照指定的顺序改变颜色?

【问题讨论】:

    标签: ios swift string nsattributedstring


    【解决方案1】:

    试试这个:

    let color : [UIColor] = [.white, .blue, .red, .orange]
    
    
    let plainString = "Hello World"
    let str = NSMutableAttributedString(string: plainString)
    
    for var i in 0..<plainString.characters.count {
        let range =  NSMakeRange(i, 1)
        let newColor = color[i % color.count]
    
        str.addAttribute(NSForegroundColorAttributeName, value: newColor, range: range)
    }
    

    【讨论】:

      【解决方案2】:

      你可以用这个:

      let text = NSMutableAttributedString(string: "ABC")
      text.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSMakeRange(0, 1))
      text.addAttribute(NSForegroundColorAttributeName, value: UIColor.yellowColor(), range: NSMakeRange(1, 2))
      thelabel.attributedText = text
      

      【讨论】:

        【解决方案3】:

        此方法会为您完成(适用于 Swift 3/Xcode 8)

        import UIKit
        
        var str = "Hello, playground"
        
        func colorText(str:String,textColors:[UIColor])->NSMutableAttributedString {
            let myMutableString = NSMutableAttributedString(string: str)
            var charNum = 0
            repeat {
                for color in textColors {
                    if charNum>=myMutableString.length {
                        return myMutableString
                    }
                    myMutableString.addAttribute(NSForegroundColorAttributeName, value: color, range: NSRange(location:charNum,length:1))
                    charNum+=1
                }
            } while true
        }
        
        
        let coloredText = colorText(str: str,textColors:[.white,.blue,.red,.orange])
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-03-17
          • 1970-01-01
          • 2023-03-20
          • 1970-01-01
          • 2017-07-22
          • 2017-03-24
          • 1970-01-01
          相关资源
          最近更新 更多