UITextView 在textview文本中插入文本
我想偶尔将文本插入 UITextView 文本对象中。例如,如果用户按下“新段落”按钮,我想插入双换行符,而不仅仅是标准的单换行符。
我该怎么办?我是否必须从 UITextView 读取字符串,对其进行变异,然后写回?那我怎么知道指针在哪里呢?
谢谢
I want to have to occasionally insert text into the UITextView text object. For example, if the user presses the "New Paragraph" button I would like to insert a double newline instead of just the standard single newline.
How can I go about such? Do i have to read the string from UITextView, mutate it, and write it back? Then how would I know where the pointer was?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
由于
UITextView
的text
属性是不可变的,因此您必须创建一个新字符串并为其设置 text 属性。 NSString 有一个实例方法(-stringByAppendingString:
),用于通过将参数附加到接收者来创建新字符串:Since the
text
property ofUITextView
is immutable, you have to create a new string and set the text property to it. NSString has an instance method (-stringByAppendingString:
) for creating a new string by appending the argument to the receiver:UITextview 有一个 insertText 方法,它尊重光标位置。
例如:
UITextview has an insertText method and it respects cursor position.
for example:
这是我实现它的方法,看起来效果很好。
Here's how I implemented it and it seems to work nicely.
对于 Swift 3.0
您可以通过调用
UITextView
实例的insertText
方法来附加文本。例子:
For Swift 3.0
You can append text by calling method
insertText
ofUITextView
Instance.Example:
这是正确答案!
光标位置也正确。
滚动位置也正确。
This is a correct answer!
The cursor position is also right.
A scroll position is also right.