ios - 如何限制swift中的光标位置?

标签 ios swift cursor uitextview

如何使用 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/

相关文章:

javascript - 如何在 react-native 中以编程方式重新加载当前页面

ios - 取消隐藏标签栏 ios swift

javascript - 如果对上一个文本进行了编辑,光标会跳到文本末尾

html - 自定义光标到整个页面

ios - 错误 : Assigning to 'CLLocationCoordinate2D' from incompatible type 'id'

ios - 在 AVCaptureMovieFileOutput 之后使用 AVPlayer 播放视频

swift - 在 tvOS 中更改 View 时如何保持选择的片段?

Android从任何游标中获取任何列的值,给出相应的id

android - 无法从 Assets 路径在 phonegap 项目中使用 jquery 加载 xml 文件

swift - 如何在 Swift 中使用精度?