ios - 使用 AttributedString 立即格式化 UITextView

标签 ios swift macos textview uitextview

我正在开发一个 macOS 富文本编辑器,它为 TextView 的每一行应用预定义的样式。

为了格式化行,我使用 NSAttributedString,然后将该字符串插入到我的 UITextView 中。为了让事情变得更容易,我使用了一个名为 SwiftRichString 的工具。 .

我的代码如下所示。它非常简单并且运行良好。

import Cocoa
import SwiftRichString
import AppKit

class ViewController: NSViewController {
    @IBOutlet var textView: NSTextView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Format the string
        let style = Style {
            $0.font = NSFont(name: "Arial", size: 20)
            $0.color = NSColor.black
            $0.alignment = .center
        }
        let attributedText = "Hello World!".set(style: style)

        // Add formatted string to the text view
        textView.textStorage?.append(attributedText)
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

}

现状:

用户正在输入格式化的行。然后,当用户点击 Return 并输入内容时,新行的格式将返回到 UITextView 的默认样式。

我想要什么:

用户正在输入特定格式的行,然后他按回车。下一行格式化为另一种即时预定义样式。

示例:

  1. 用户正在输入标题行。当前样式为(Arial、粗体、20pt)。
  2. 他点击了返回
  3. 下一行应使用预定义样式(Arial、12pt)将样式设置为普通文本。

重要说明:

在上面的代码中,我能够轻松地格式化该行,因为它是硬编码的。我真正的问题是,如何立即格式化下一行,因为下一行将由用户输入。在用户开始编写之前,应将样式应用于下一行。

最佳答案

好吧,我刚刚弄清楚如何使用 typingAttributtes 来解决这个问题(感谢 @Larme 的提示)。

   // Define next attributes
   let attributes: [NSAttributedString.Key: Any] = [
       .foregroundColor: NSColor.red,
       .font: NSFont(name: "Arial", size: 12)!,
   ]
   
   // Assign attributes to the text view typing attributes
   textView.typingAttributes = attributes

非常简单!

关于ios - 使用 AttributedString 立即格式化 UITextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64748034/

相关文章:

iphone - box2d 圆形物体卡在角落里

android - 文本输入在 Flex Mobile 项目中显示 block 而不是阿拉伯文本

xcode - 简单反射测试游戏应用中的 NSDataStorage 问题

ios - GPUImage Lookup Filter - 创建大于 512² 颜色的颜色深度

macos - 在 OS X El Capitan 上为 Visual Studio Code 设置 OmniPascal 扩展

iphone - 具有大型 JSON 数据的 UITableView 字母索引

ios - 将segue动画更改为 "Show",但它卡在 "Modal"

ios - CloudKit 的单元测试

ios - 当元素被激活时如何获取indexpath.row?

java - 更新 Java 中的 Midi 设备列表