我为 View Controller 的生命周期做了功课。我使用标签栏来切换 Controller 。并且在切换 Controller 时, TextView 的标签显示生命周期方法。
现在我想更改 TextView 中表达式“First Controller”、“Second Controller”、“Third Controller”的颜色文本,以便无论我切换到哪个 Controller ,颜色都保持不变。
怎么做?
import UIKit
class FirstViewController: UIViewController {
@IBOutlet var firstTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
FromCodeToScreen.shared.printMessage(textView: firstTextView, viewController: self)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
FromCodeToScreen.shared.printMessage(textView: firstTextView, viewController: self)
}
override func viewDidAppear(_ animated: Bool) {
super.viewWillAppear(animated)
FromCodeToScreen.shared.printMessage(textView: firstTextView, viewController: self)
}
// And similar code in all of the other lifecycle methods
}
import UIKit
class FromCodeToScreen: NSObject {
static let shared = FromCodeToScreen()
private var arrayForData = [String]()
private override init() {
super.init()
}
func printMessage(textView: UITextView, viewController: UIViewController, function: String = #function) {
arrayForData.append((viewController.title ?? "nil") + " - " + (function))
let string = arrayForData.joined(separator: "\n")
textView.text = string
textViewScrollToBottom(textView)
}
}
最佳答案
将 arrayForData 字符串数组更改为 NSAttributedString。
class FromCodeToScreen: NSObject {
static let shared = FromCodeToScreen()
private var arrayForData = [NSAttributedString]()
private override init() {
super.init()
}
func printMessage(textView: UITextView, viewController: UIViewController, function: String = #function) {
let color = viewController.view.backgroundColor ?? .white
let attStr = NSMutableAttributedString(string: viewController.title ?? "nil", attributes: [.foregroundColor : color])
attStr.append(NSAttributedString(string: " - " + function + "\n"))
arrayForData.append(attStr)
textView.attributedText = arrayForData.reduce(into: NSMutableAttributedString()) { $0.append($1) }
textViewScrollToBottom(textView)
}
}
关于swift - 如何在 TextView 中更改某些文本的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55905000/