如何动态设置UIScrollView的内容大小

Rog*_*Lee 30 iphone objective-c uiscrollview uiview

我有疑问UIScrollview.

故事是我有一个UIView名为ChartsView,我通过覆盖方法自己重新绘制它drawRect().绘图的内容是动态生成的.所以直到运行时我才知道它的大小.问题是如何/在哪里可以动态设置其超级视图(scrollView)的内容大小?有什么想法吗?

    - (void)viewDidLoad
    {
        [super viewDidLoad];

// not this way. it's fixed size.....
        ChartsView *chartsView = [[ChartsView alloc]initWithFrame:CGRectMake(0, 0, 320, 800)]; 

        self.scrollView.contentSize = chartsView.frame.size;

        [self.scrollView addSubview:chartsView];

    }
Run Code Online (Sandbox Code Playgroud)

IOS*_*cks 60

一个更简单的方法

- (void)viewDidLoad
{
    float sizeOfContent = 0;
    UIView *lLast = [scrollView.subviews lastObject];
    NSInteger wd = lLast.frame.origin.y;
    NSInteger ht = lLast.frame.size.height;

    sizeOfContent = wd+ht;

    scrollView.contentSize = CGSizeMake(scrollView.frame.size.width, sizeOfContent);
}
Run Code Online (Sandbox Code Playgroud)

  • lastObject返回在子视图数组中索引的最后一个对象,而不是屏幕上最底部的子视图.实际上,lastObject与视图的位置无关,使用它是错误的. (16认同)

Cha*_*tas 12

不能100%保证scrollView.subviews数组中的最后一个对象将返回滚动视图中的最高y轴对象。子视图数组按Z-Index排列(即,子视图数组中的最后一个对象将是堆叠最高的对象,并且将是滚动视图的子视图中最顶部的子视图。相反,使用基本的排序函数会更准确遍历子视图并获得具有最高y坐标的对象。

斯威夫特4

extension UIScrollView {
    func updateContentView() {
        contentSize.height = subviews.sorted(by: { $0.frame.maxY < $1.frame.maxY }).last?.frame.maxY ?? contentSize.height
    }
}
Run Code Online (Sandbox Code Playgroud)

用法(在viewDidLayoutSubviews内容大小更新时或其中):

myScrollView.updateContentView()
Run Code Online (Sandbox Code Playgroud)


Cul*_*tes 6

迅捷(2.0)

@IBOutlet weak var btnLatestButton: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()

    let height = btnLatestButton.frame.size.height
    let pos = btnLatestButton.frame.origin.y
    let sizeOfContent = height + pos + 10
    scrollview.contentSize.height = sizeOfContent

}
Run Code Online (Sandbox Code Playgroud)

当然,您可以在滚动视图中获得固定数量的视图.IOS Rocks方法可用,但对我不好,创造了更多空间,然后我需要.

    let lastView : UIView! = scrollview.subviews.last
    let height = lastView.frame.size.height
    let pos = lastView.frame.origin.y
    let sizeOfContent = height + pos + 10
    scrollview.contentSize.height = sizeOfContent
Run Code Online (Sandbox Code Playgroud)


MrW*_*med 1

尝试这个

- (void)viewDidLoad
        {
            [super viewDidLoad];

    // not this way. it's fixed size.....
            ChartsView *chartsView = [[ChartsView alloc]initWithFrame:CGRectMake(0, 0, 320, 800)]; 

            self.scrollView.contentSize = chartsView.frame.size;
            [self.scrollView setNeedsDisplay];
            [self.scrollView addSubview:chartsView];

    }
Run Code Online (Sandbox Code Playgroud)