你能帮助我吗,我试着制作多色文字,但是我收到一个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)
}
}
答案 0 :(得分:3)
你需要这样的东西,使用NSMutableAttributedString
允许你做这样的事情
这是代码
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")
我希望这有助于你
答案 1 :(得分:-1)
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
}
用法:
let attributedString = getAttribute([["H" : UIColor.black], ["i" : UIColor.gray]])
button.setAttributedTitle(attributedString, for: .normal)
label.attributedText = attributedString