【问题标题】:Find text in array and return index number在数组中查找文本并返回索引号
【发布时间】:2018-03-07 00:35:00
【问题描述】:

我在文本视图中显示由\n 或换行符分隔的字符串数组。感谢\n,如果文本视图中有空间,每个字符串都有自己的行。但是,如果 textview 的宽度小于字符串,那么 textview 会自动将行换行到下一行,这样实际上字符串需要两行。到目前为止没有任何问题。

但是,如果有人触摸它,我想抓住它。如果字符串适合一条线,它工作正常。但是,如果字符串已被 textview 分成两行,如果用户触摸顶行,我需要附加下面的行以获取整个字符串。或者如果用户触及底线,我需要获取并添加上一个以获得整个字符串。

谁能提出正确的方法来做到这一点?

这是我的代码,它抓取了人触摸的线,但是,它只触摸了线并且在尝试计算数组中字符串的索引时失败。

感谢您的任何建议:

- (void) handleTap:(UITapGestureRecognizer *)recognizer{
    UITextView *textView =  (UITextView *)recognizer.view;
    CGPoint location = [recognizer locationInView:textView];
    CGPoint position = CGPointMake(location.x, location.y);
     UITextPosition *tapPosition = [textView closestPositionToPoint:position];

    UITextRange *textRange = [textView.tokenizer rangeEnclosingPosition:tapPosition withGranularity:UITextGranularityLine inDirection:UITextLayoutDirectionRight];
//In following line, I am not getting the full text in the string, only the text of that line.  I need to get the whole string.
    NSString *tappedLine = [textView textInRange:textRange];
    NSArray* myArray  = [self.listSub.text componentsSeparatedByString:@"\n"];     
      NSInteger indexOfTheObject = [myArray indexOfObject: tappedLine];
//If the tapped line is not the same thing as the string, the above index becomes huge number like 94959494994949494 ie an error, not the index I want.
    }

【问题讨论】:

  • 你有行文本表示数组的对象与整行文本?

标签: ios objective-c nsarray uitextview


【解决方案1】:

这确实是可能的。

首先需要将粒度改为UITextGranularityParagraph

UITextRange *textRange = [textView.tokenizer rangeEnclosingPosition:tapPosition withGranularity:UITextGranularityParagraph inDirection:UITextLayoutDirectionRight];

这将为您返回用户点击的整行文本,无论他们在哪里点击。

但是,此文本将包含标记段落结尾的尾随 \n 字符。在将文本与数组进行比较之前,您需要删除它。将上面代码的最后一行替换为这两行:

NSString *trimmedLine = [tappedLine stringByTrimmingCharactersInSet:
                              [NSCharacterSet newlineCharacterSet]];
NSInteger indexOfTheObject = [myArray indexOfObject: trimmedLine];

【讨论】:

  • 哈利路亚!谢谢!
【解决方案2】:

您可能想考虑使用 UITableView https://developer.apple.com/documentation/uikit/uitableview

您可以为数组中的每个条目创建一个带有文本视图的单元格,当用户与任何单元格交互时,您将获得委托调用

【讨论】:

  • 谢谢。我希望在没有表格视图的情况下做到这一点。
猜你喜欢
  • 1970-01-01
  • 2012-02-13
  • 2012-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-10
  • 2017-12-27
  • 1970-01-01
相关资源
最近更新 更多