首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当用户键入新行时,如何向UITextView添加自动缩进?

问当用户键入新行时,如何向UITextView添加自动缩进?
EN

Stack Overflow用户
提问于 2014-12-06 18:03:21
回答 2查看 1.3K关注 0票数 4

当用户键入新行时,如何向UITextView添加自动缩进?示例:

代码语言:javascript
复制
line1
  line2 <user has typed "Enter">
  <cursor position>
    line3 <user has typed "Enter">
    <cursor position>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-12-06 18:26:55

虽然在这种情况下,OP似乎实际上并不是在寻找标准缩进,但我将这个留给未来的答案寻求者。

下面是如何在每个换行符之后自动添加缩进的方法。我从我最近类似的answer about automatically adding bullet points at every newline中改编了这个答案。

代码语言:javascript
复制
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {

    // If the replacement text is "\n" thus indicating a newline...
    if ([text isEqualToString:@"\n"]) {

        // If the replacement text is being added to the end of the
        // text view's text, i.e. the new index is the length of the
        // old text view's text...
        if (range.location == textView.text.length) {
            // Simply add the newline and tab to the end
            NSString *updatedText = [textView.text stringByAppendingString:@"\n\t"];
            [textView setText:updatedText];
        }

        // Else if the replacement text is being added in the middle of
        // the text view's text...
        else {

            // Get the replacement range of the UITextView
            UITextPosition *beginning = textView.beginningOfDocument;
            UITextPosition *start = [textView positionFromPosition:beginning offset:range.location];
            UITextPosition *end = [textView positionFromPosition:start offset:range.length];
            UITextRange *textRange = [textView textRangeFromPosition:start toPosition:end];

            // Insert that newline character *and* a tab
            // at the point at which the user inputted just the
            // newline character
            [textView replaceRange:textRange withText:@"\n\t"];

            // Update the cursor position accordingly
            NSRange cursor = NSMakeRange(range.location + @"\n\t".length, 0);
            textView.selectedRange = cursor;

        }

        // Then return "NO, don't change the characters in range" since
        // you've just done the work already
        return NO;
    }

    // Else return yes
    return YES;
}
票数 3
EN

Stack Overflow用户

发布于 2014-12-14 19:17:13

对于第一行,您必须编写以下代码:

代码语言:javascript
复制
- (void)textViewDidBeginEditing(UITextView *)textView
{
    if ([textView.text isEqualToString:@""])
    {
        [textView setText:@"\t"];
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27334713

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档