本文介绍了Swift 中的多色文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能帮我吗,我试图制作多色文本,但我收到一个 SIGABRT 错误,但绝对不知道它来自哪里.代码如下:

Can you please help me, I tried to make multicolour text but I get a SIGABRT error but absolutely don't know from were it comes from. Here's the code:

class ViewController: UIViewController {

@IBOutlet weak var ColoredTxt: UILabel!
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    var Timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: ColoredTxt, selector: Selector("ColoredTxt"), userInfo: nil, repeats: true)

}


@IBAction func Btn(sender: AnyObject) {

    let redValue = CGFloat(drand48())
    let greenValue = CGFloat(drand48())
    let blueValue = CGFloat(drand48())

    ColoredTxt.textColor = UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: 1.0)
}


func randomColor() {

    let redValue = CGFloat(drand48())
    let greenValue = CGFloat(drand48())
    let blueValue = CGFloat(drand48())

    ColoredTxt.textColor = UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: 1.0)

    }
}

推荐答案

你需要这样的东西,使用 NSMutableAttributedString 可以让你做这样的事

You need something like this, using NSMutableAttributedString allow you do things like this

这是代码

   func multicolorString(originalString : String) ->NSMutableAttributedString
    {
        let mutableString = NSMutableAttributedString(string: originalString)

        for index in 0..<originalString.characters.count
        {
            if(index % 2 == 0)
            {
                mutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.green, range: NSMakeRange(index, 1))
            }else if(index % 3 == 0)
            {
                mutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blue, range: NSMakeRange(index, 1))
            }else{
                mutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: NSMakeRange(index, 1))
            }
        }

        return mutableString
    }

然后像这样使用

self.ColoredTxt.attributedText = self.multicolorString("Owner")

希望对你有帮助

这篇关于Swift 中的多色文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-07 17:05