Подтвердить что ты не робот

Размер содержимого UITextView отличается от iOS7

Я использую UITextView, который будет расширяться, нажав кнопку "больше". Проблема заключается в следующем:

На iOS6 я использую это,

self.DescriptionTextView.text =  @"loong string";

if(self.DescriptionTextView.contentSize.height>self.DescriptionTextView.frame.size.height) { 
    //set up the more button
}

Проблема в том, что на iOS7 contentSize.height возвращает другое значение (намного меньше), чем значение, которое оно возвращает на iOS6. Почему это? Как это исправить?

4b9b3361

Ответ 1

Свойство размера содержимого больше не работает так же, как на iOS 6. Использование sizeToFit, как показывают другие, может работать или не работать в зависимости от ряда факторов.

Это не сработало для меня, поэтому я использую это вместо:

- (CGFloat)measureHeightOfUITextView:(UITextView *)textView
{
    if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1)
    {
        // This is the code for iOS 7. contentSize no longer returns the correct value, so
        // we have to calculate it.
        //
        // This is partly borrowed from HPGrowingTextView, but I've replaced the
        // magic fudge factors with the calculated values (having worked out where
        // they came from)

        CGRect frame = textView.bounds;

        // Take account of the padding added around the text.

        UIEdgeInsets textContainerInsets = textView.textContainerInset;
        UIEdgeInsets contentInsets = textView.contentInset;

        CGFloat leftRightPadding = textContainerInsets.left + textContainerInsets.right + textView.textContainer.lineFragmentPadding * 2 + contentInsets.left + contentInsets.right;
        CGFloat topBottomPadding = textContainerInsets.top + textContainerInsets.bottom + contentInsets.top + contentInsets.bottom;

        frame.size.width -= leftRightPadding;
        frame.size.height -= topBottomPadding;

        NSString *textToMeasure = textView.text;
        if ([textToMeasure hasSuffix:@"\n"])
        {
            textToMeasure = [NSString stringWithFormat:@"%@-", textView.text];
        }

        // NSString class method: boundingRectWithSize:options:attributes:context is
        // available only on ios7.0 sdk.

        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        [paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping];

        NSDictionary *attributes = @{ NSFontAttributeName: textView.font, NSParagraphStyleAttributeName : paragraphStyle };

        CGRect size = [textToMeasure boundingRectWithSize:CGSizeMake(CGRectGetWidth(frame), MAXFLOAT)
                                                  options:NSStringDrawingUsesLineFragmentOrigin
                                               attributes:attributes
                                                  context:nil];

        CGFloat measuredHeight = ceilf(CGRectGetHeight(size) + topBottomPadding);
        return measuredHeight;
    }
    else
    {
        return textView.contentSize.height;
    }
}

Ответ 2

Попробуйте ответить в следующей ссылке, layoutIfNeeded следует вызвать до contentSize.

iOS7 UITextView contentize.height альтернатива

Ответ:

В iOS7 UITextView используется NSLayoutManager для текста макета:

// If YES, then the layout manager may perform glyph generation and layout for a given portion of the text, without having glyphs or layout for preceding portions.  The default is NO.  Turning this setting on will significantly alter which portions of the text will have glyph generation or layout performed when a given generation-causing method is invoked.  It also gives significant performance benefits, especially for large documents.
@property(NS_NONATOMIC_IOSONLY) BOOL allowsNonContiguousLayout;

отключить allowsNonContiguousLayout, чтобы исправить contentSize:

textView.layoutManager.allowsNonContiguousLayout = NO;

Ответ 3

Эта ссылка кажется ответом.

Вы должны использовать sizeToFit перед использованием contentSize.

Ответ 4

Попробуйте использовать следующий код. Его работа будет работать как на iOS6, так и на 7, пожалуйста, попробуйте.

CGSize myTextViewSize = [self.myTextView sizeThatFits:CGSizeMake(self.myTextView.frame.size.width, FLT_MAX)];
self.myTextView.height = myTextViewSize.height;
NSLog(@"%f", self.myTextView.height);