我为视图控制器的生命周期做了作业。我使用标签栏来切换控制器。并且在切换控制器时,文本标签会显示生命周期方法。
现在,我想在文本视图中更改表达式“第一控制器”,“第二控制器”,“第三控制器”的颜色文本,以便无论我切换到哪个控制器,颜色都保持不变。
如何做到?
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)
}
}
答案 0 :(得分:2)
将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)
}
}
答案 1 :(得分:0)
尝试一下
let text = "This is a colorful attributed string"
let attributedText =
NSMutableAttributedString.getAttributedString(fromString: text)
attributedText.apply(color: .red, subString: "This")
//Apply yellow color on range
attributedText.apply(color: .yellow, onRange: NSMakeRange(5, 4))
For more detail click here: https://github.com/iOSTechHub/AttributedString
答案 2 :(得分:-2)
尝试:
firstTextView.textColor = UIColor.red
将其应用于每个ViewController的viewDidLoad()。
将颜色更改为所需的颜色。