mri*_*ddi 15 objective-c nsstring uitextview ios
我尝试检测托架在UITextView中的新行.我可以通过比较总后来宽度和UITextView宽度来检测它:
CGSize size = [textView.text sizeWithAttributes:textView.typingAttributes];
if(size.width > textView.bounds.size.width)
NSLog (@"New line");
Run Code Online (Sandbox Code Playgroud)
但它不能正常工作,因为-sizeWithAttributes:textView只返回没有缩进宽度的字母宽度.请帮忙解决这个问题.
n00*_*mer 30
我就是这样做的:
UITextPosition最后一个角色.caretRectForPosition给你UITextView.CGRect变量并最初存储CGRectZero在其中.textViewDidChange:方法中,caretRectForPosition:通过传递调用UITextPosition.CGRect变量中的当前值进行比较.如果caretRect的新y原点大于最后一个,则表示已达到新行.示例代码:
CGRect previousRect = CGRectZero;
- (void)textViewDidChange:(UITextView *)textView{
UITextPosition* pos = yourTextView.endOfDocument;//explore others like beginningOfDocument if you want to customize the behaviour
CGRect currentRect = [yourTextView caretRectForPosition:pos];
if (currentRect.origin.y > previousRect.origin.y){
//new line reached, write your code
}
previousRect = currentRect;
}
Run Code Online (Sandbox Code Playgroud)
此外,您应该在此处阅读UITextInput协议参考文档.这是神奇的,我告诉你.
如果您对此有任何其他问题,请与我们联系.
对于Swift使用此
previousRect = CGRectZero
func textViewDidChange(textView: UITextView) {
var pos = textView.endOfDocument
var currentRect = textView.caretRectForPosition(pos)
if(currentRect.origin.y > previousRect?.origin.y){
//new line reached, write your code
}
previousRect = currentRect
}
Run Code Online (Sandbox Code Playgroud)
应允@ n00bProgrammer在Swift-4与更精确的断线检测.
@ n00bProgrammer的答案是完美的,除了一件事,当用户开始输入第一行时,它会有不同的反应,它也提出了这Started New Line一点.
克服问题,这里是精炼的代码
var previousRect = CGRect.zero
func textViewDidChange(_ textView: UITextView) {
let pos = textView.endOfDocument
let currentRect = textView.caretRect(for: pos)
self.previousRect = self.previousRect.origin.y == 0.0 ? currentRect : self.previousRect
if currentRect.origin.y > self.previousRect.origin.y {
//new line reached, write your code
print("Started New Line")
}
self.previousRect = currentRect
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15247 次 |
| 最近记录: |