swift - 如何在 TextView 中更改某些文本的颜色?

标签 swift uitextview

我为 View Controller 的生命周期做了功课。我使用标签栏来切换 Controller 。并且在切换 Controller 时, TextView 的标签显示生命周期方法。

现在我想更改 TextView 中表达式“First Controller”、“Second Controller”、“Third Controller”的颜色文本,以便无论我切换到哪个 Controller ,颜色都保持不变。

https://youtu.be/Od_bFlaA-kY

怎么做?

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

enter image description here

关于swift - 如何在 TextView 中更改某些文本的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55905000/

相关文章:

ios - 字符串 boundingRect 计算出的高度与 UITextView 内容高度不匹配

ios - 如何将 UIButton.isSelectable 与 RXSwift 绑定(bind)

ios - 如何同时或单独控制两个选择器 View 内容?

ios - 是否可以在 UITextview 链接选择上设置清除颜色?

ios - 无法从 iOS 中的 UITextView 中获取已删除的字符

ios - 从 Xcode 11.1 升级到 Xcode 11.2 后,应用程序因 _UITextLayoutView 崩溃

ios - 在 Swift 的外部方法中获取当前 ViewController

swift - 为 UISearchBar 设置 cornerRadius?

xcode swift : how to display a website as pop-over

iphone - UIMenuController 未显示 UIPasteBoard 已清除 iPhone 应用程序?