UITextView's text going beyond bounds

后端 未结 7 1468
深忆病人
深忆病人 2020-12-30 01:24

I have a non-scrollable UITextView with it\'s layoutManager maximumNumberOfLines set to 9, which works fine, but, I cannot seem to find a method in NSLayoutManager that rest

7条回答
  •  感情败类
    2020-12-30 02:24

    You will need to do this yourself. Basically it would work like this:

    1. In your UITextViewDelegate's textView:shouldChangeTextInRange:replacementText: method find the size of your current text (NSString sizeWithFont:constrainedToSize: for example).
    2. If the size is larger than you allow return FALSE, otherwise return TRUE.
    3. Provide your own feedback to the user if they type something larger than you allow.

    EDIT: Since sizeWithFont: is deprecated use boundingRectWithSize:options:attributes:context:

    Example:

    NSString *string = @"Hello World"; 
    
    UIFont *font = [UIFont fontWithName:@"Helvetica-BoldOblique" size:21];
    
    CGSize constraint = CGSizeMake(300,NSUIntegerMax);
    
    NSDictionary *attributes = @{NSFontAttributeName: font};
    
    CGRect rect = [string boundingRectWithSize:constraint 
                                       options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)  
                                    attributes:attributes 
                                       context:nil];
    

提交回复
热议问题