如何使用 caretRectForPosition
方法或任何其他方法在 swift 中限制光标的最小位置。假设,我有一个包含一些内容的 TextView ,如果用户试图将光标移动到第三个位置之前,它不应该移动。这怎么可能?阅读了几篇关于它的文章,但没有回答我的问题。
最佳答案
我假设通过限制光标的最小位置,你的意思是在示例字符串之外:“这是一个示例字符串”——你想确保用户所做的选择在某个 NSRange 内?
UITextView 有一个委托(delegate)协议(protocol),其中包含一个在选择更改时调用的方法:
- (void)textViewDidChangeSelection:(UITextView *)textView
您可以实现委托(delegate),监听此方法,然后执行如下操作:
//swift
func textViewDidChangeSelection(textView: UITextView) {
let minLocation = 3
let currentRange = textView.selectedRange
if (currentRange.location < minLocation) {
let lengthDelta = (minLocation - currentRange.location)
//Minus the number of characters moved so the end point of the selection does not change.
let newRange = NSMakeRange(minLocation, currentRange.length - lengthDelta);
//Should use UITextInput protocol
textView.selectedRange = newRange;
}
}
//objective-C
- (void)textViewDidChangeSelection:(UITextView *)textView
{
NSUInteger minLocation = 3;//your value here obviously
NSRange currentRange = textView.selectedRange;
if (currentRange.location < minLocation) {
NSUInteger lengthDelta = (minLocation - currentRange.location);
//Minus the number of characters moved so the end point of the selection does not change.
NSRange newRange = NSMakeRange(minLocation, currentRange.length - lengthDelta);
//Should use UITextInput protocol
UITextPosition *location = [textView positionFromPosition:[textView beginningOfDocument] offset: newRange.location];
UITextPosition *length = [textView positionFromPosition:location offset:newRange.length];
[textView setSelectedTextRange:[textView textRangeFromPosition:location toPosition:length]];
}
}
您也可以使用类似的方法来施加最大选择/长度等。
这意味着在之前的示例字符串中,您将无法选择字符串开头的任何“Thi”。
有关 UITextView 委托(delegate)的更多信息,请参见此处: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITextViewDelegate_Protocol/
关于ios - 如何限制swift中的光标位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37639076/