如何在UITextView中的每个新行添加无序列表或项目符号点

Hor*_*ray 3 xcode objective-c ios swift

所以基本上我想在一个无序列表中添加一个UITextView.另一个UITextView我想添加一个有序列表.

我尝试使用这个代码,但它只是在用户第一次按下Enter键后给了我一个项目符号(不仅仅是那个),我甚至无法退格.

- (void)textViewDidChange:(UITextView *)textView
{
    if ([myTextField.text isEqualToString:@"\n"]) {
        NSString *bullet = @"\u2022";
        myTextField.text = [myTextField.text stringByAppendingString:bullet];
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您只找到使用Swift执行它的方法,那么随意发布Swift版本的代码.

Lyn*_*ott 5

问题是你正在使用

if ([myTextField.text isEqualToString:@"\n"]) {
Run Code Online (Sandbox Code Playgroud)

作为您的条件,所以如果整个myTextField.text等于"\n" ,则执行该块.但是,你的全部myTextField.text只等于"\n",如果您还没有输入任何东西,但 "\n".这就是为什么现在,这段代码只是在"用户第一次按下回车"时工作; 当你说"我甚至不能退缩它"时,问题实际上是由于同样的条件仍在满足,因此要求重新添加子弹点textViewDidChange:.

在这种情况下,不要使用textViewDidChange:我推荐使用shouldChangeTextInRange:,这样你就可以知道替换文本是什么,无论它在UITextView文本字符串中的位置.通过使用此方法,即使在文本块的中间输入换行符,也可以自动插入项目符号点...例如,如果用户决定输入一堆信息,则跳回几行要输入更多信息,然后尝试在两者之间按换行,以下内容仍应有效.这是我的建议:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {

    // If the replacement text is "\n" and the
    // text view is the one you want bullet points
    // for
    if ([text isEqualToString:@"\n"]) {

        // If the replacement text is being added to the end of the
        // text view, 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 bullet point to the end
            NSString *updatedText = [textView.text stringByAppendingString:@"\n\u2022 "];
            [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 bullet point
            // at the point at which the user inputted just the
            // newline character
            [textView replaceRange:textRange withText:@"\n\u2022 "];

            // Update the cursor position accordingly
            NSRange cursor = NSMakeRange(range.location + @"\n\u2022 ".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;
}
Run Code Online (Sandbox Code Playgroud)