问题
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)
}
}
回答1:
You need something like this, using NSMutableAttributedString
allow you do things like this
Here is the code
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
}
and then use like this
self.ColoredTxt.attributedText = self.multicolorString("Owner")
I hope this helps you
回答2:
func getAttribute(_ array: [[String: UIColor]]) -> NSAttributedString {
let attributedString = NSMutableAttributedString(string: "" )
for item in array {
let text = item.keys.first ?? ""
let color = item.values.first ?? UIColor.black
let attributed = NSMutableAttributedString(string: text, attributes: [NSForegroundColorAttributeName : color])
attributedString.append(attributed)
}
return attributedString
}
Usage:
let attributedString = getAttribute([["H" : UIColor.black], ["i" : UIColor.gray]])
button.setAttributedTitle(attributedString, for: .normal)
label.attributedText = attributedString
来源:https://stackoverflow.com/questions/42306760/multicolour-text-in-swift