简体   繁体   中英

Multiple lines deletion in UITextView

I am trying to adjust height of UITextView programmatically in objective c when the user types/deletes characters. It works perfectly for me as long as user does not delete multiple lines at a time. So, the main question is how could we detect multiple lines deletion in UITextView and get this number of lines (adjustment of height is easy afterwards).

I don't know specifically for multiple lines, but this method could help you know the change in range of characters in UITextView

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
 {
  char toDelete = [textView.text characterAtIndex:range.location];

    int duplicateCharCount = 0;
    for(int i =range.location-1; i>=0; i--) {

        if([textView.text characterAtIndex:i] == toDelete) {
            duplicateCharCount++;
        } else {
            break;
        }  
    }

    NSRange newRange = NSMakeRange(0, range.location - duplicateCharCount);
    [textView setText:[textView.text substringWithRange:newRange]];

    return NO;
} else {
    return YES;
}

But for your scenario, you can calculate number of lines by knowing frame size of your textview like this:

UIFont *font = [UIFont boldSystemFontOfSize:11.0];
CGSize size = [string sizeWithFont:font 
                  constrainedToSize:myUITextView.frame.size 
                  lineBreakMode:UILineBreakModeWordWrap]; // default mode
float numberOfLines = size.height / font.lineHeight;

Use below code in textViewDidChange delegate method of UITextView :

- (void)textViewDidChange:(UITextView *)textView
{

    CGFloat fixedWidth = textView.frame.size.width;
    CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
    CGRect newFrame = textView.frame;
    newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
    textView.frame = newFrame;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM