UIScrollView contentSize not working

前端 未结 15 1613
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 06:18

I put a UIScrollView in my nib\'s view, and linked it to a an IBOutlet property.

Now, when I do this in my viewDidLoad

15条回答
  •  猫巷女王i
    2020-11-28 07:01

    Use this code. ScrollView setContentSize should be called async in main thread.

    Swift:

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
    
        DispatchQueue.main.async {
            var contentRect = CGRect.zero
    
            for view in self.scrollView.subviews {
               contentRect = contentRect.union(view.frame)
            }
    
            self.scrollView.contentSize = contentRect.size
        }
    }
    

    Objective C:

     - (void)viewDidLayoutSubviews {
         [super viewDidLayoutSubviews];
    
         dispatch_async(dispatch_get_main_queue(), ^ {
                            CGRect contentRect = CGRectZero;
    
                            for(UIView *view in scrollView.subviews)
                               contentRect = CGRectUnion(contentRect,view.frame);
    
                               scrollView.contentSize = contentRect.size;
                           });
    }
    

提交回复
热议问题