iOS: how to change the size of the UIScrollView content?

后端 未结 3 805
心在旅途
心在旅途 2021-02-06 13:00

I\'m now trying to create my own Text panel (with code highlighting and so on).

In fact everything is ready except one thing - scrolling

What I\'ve done: created

相关标签:
3条回答
  • 2021-02-06 13:39

    Set your text field autoresizingMask property to flexible height and width:

    [textField setAutoResizingMask:UIViewAutoResizingFlexibleHeight | UIViewAutoResizingFlexibleWidth];
    

    This should expand the view automatically when you change it's parent's size (the scrollView's contentSize)

    Otherwise try:

    [textField setFrame:CGRectMake(0, 0, scrollView.contentSize.width, scrollView.contentSize.height)];
    

    just after you change the scroll view's contentsize.

    0 讨论(0)
  • 2021-02-06 13:45

    Part 1:

    The scroll view's content size is not actually related to the size or position of the views it contains. If you want to change the size of the content view as well as the scroll view's content, you need to call two different methods.

    CGSize newSize;
    UIScrollView *scrollView;
    // assume self is the content view
    CGRect newFrame = (CGRect){CGPointZero,newSize}; // Assuming you want to start at the top-left corner of the scroll view. Change CGPointZero as appropriate
    [scrollView setContentSize:newSize]; // Change scroll view's content size
    [self setFrame:newFrame]; // Change views actual size
    

    Part 2:

    setNeedsDisplay marks the entire view as needing display. To cause it to display only the visible part, you need to use setNeedsDisplayInRect:visibleRect.
    Assuming the view is at the top-left corner (its frame's origin is 0) and the scroll view does not allow zooming, the visible rect can be found using the scroll view's content offset and bounds size.

    CGRect visibleRect;
    visibleRect.origin = [scrollView contentOffset];
    visibleRect.size = [scrollView bounds].size;
    [self setNeedsDisplayInRect:visibleRect];
    

    You could also choose to draw a part of the visible rect if only part changes.

    0 讨论(0)
  • 2021-02-06 14:02

    It's simpler than you think, for example you have an UITextView called "textDesc" inside your UIScrollView, and you want to know the size of content, so next step will looks like that:

    int contentHeight = textDesc.frame.size.height + textDesc.frame.origin.y;
    

    After calculating the size of textDesc, just set it:

    [scrollView setContentSize:(CGSizeMake(320, contentHeight))];
    

    That's all, now your scrollView know the size of your text inside him, and will resize automatically, hope this helps, good luck.

    0 讨论(0)
提交回复
热议问题