从滚动文本视图中读取文本并在 macOS 中插入特定字符串

read text from scroll Textview and insert specific string in macOS

您好,我想在 MacOS 中根据用户输入创建一个字符串,swift。

例如,如果用户输入了一个字符串

” 第 1 行 fadsjkf

第 2 行 fasdjkfla

第 3 行 fasdnfkdf

我想读取每行中的字符串并插入一些字符或字符串,如

” XYZ 1 号线 fadsjkf

农行2号线fasdjkfla

DEF 3 号线 fasdnfkdf

如何实现这个功能?

在你的例子中,用户输入是在 3 行吗?如果是这样,您可以将字符串拆分为一个数组,在每个项目的开头添加文本并重新组合一个字符串。

会是这样的:

let someText = """
Line 1 fadsjkf
Line 2 fasdjkfla
Line 3 fasdnfkdf
"""
// May be your text comes as let someText = "Line 1 fadsjkf\nLine 2 fasdjkfla\nLine 3 fasdnfkdf"

let toBeAppended = ["XYZ", "ABC", "DEF"] // Do you want to compute automatically ?
var lines = someText.split(separator: "\n").map { String([=10=]) }
var newLines = ""

for (iLine, line) in lines.enumerated() {
    let newLine = toBeAppended[iLine] + " " + line
    newLines = newLines + newLine + "\n"
}
print(newLines)

并得到:

XYZ Line 1 fadsjkf
ABC Line 2 fasdjkfla
DEF Line 3 fasdnfkdf

已编辑

如果您想要超过 3 行且行数未定:

let someText = "Line 1 fadsjkf\nLine 2 fasdjkfla\nLine 3 fasdnfkdf\nLine 4 fasdjkflaa\nLine 5 fasdjkflab\nLine 6 fasdjkflac\nLine 7 fasdjkflad\nLine 8 fasdjkflae\nLine 9 fasdjkflaf\nLine 10 fasdjkflag\nLine 11 fasdjkflah\nLine 12 fasdjkflai"
let toBeAppended = ["XYZ", "ABC", "DEF", "GHI", "JKL", "MNO", "PQR", "STU", "VWX", "YZ@"] // 9 here, up to you to add more ; beyond this, add for instance @@@
var lines = someText.split(separator: "\n").map { String([=12=]) }
var newLines = ""

for (iLine, line) in lines.enumerated() {
    let newLine = iLine < toBeAppended.count ? toBeAppended[iLine] + " " + line : "@@@ " + line
    newLines = newLines + newLine + "\n"
}
print(newLines)

你得到:

XYZ Line 1 fadsjkf
ABC Line 2 fasdjkfla
DEF Line 3 fasdnfkdf
GHI Line 4 fasdjkflaa
JKL Line 5 fasdjkflab
MNO Line 6 fasdjkflac
PQR Line 7 fasdjkflad
STU Line 8 fasdjkflae
VWX Line 9 fasdjkflaf
YZ@ Line 10 fasdjkflag
@@@ Line 11 fasdjkflah
@@@ Line 12 fasdjkflai