您能帮我吗,我尝试制作多色文本,但出现SIGABRT错误,但绝对不知道它是从哪里来的。这是代码:

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可以执行这样的事情

ios - Swift中的多色文字-LMLPHP

这是代码

   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")

我希望这可以帮助你

关于ios - Swift中的多色文字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42306760/

10-10 06:54