Swift - UIScrollView not scrolling

2019-03-14 08:56发布

My UIScrollView wont scroll down. I dont know why. I already followed apple documentation regarding to this issue.

@IBOutlet weak var scroller: UIScrollView!

    override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

}

override func viewDidLayoutSubviews() {
    scroller.scrollEnabled = true
    // Do any additional setup after loading the view
    scroller.contentSize = CGSizeMake(400, 2300)
}

Please advice. Thank you.

10条回答
Lonely孤独者°
2楼-- · 2019-03-14 09:19

I do not know it is a good solution, but you can try to set headerview to empty UITableView.

let scrollView: UIView = UIView(frame: CGRectMake(0, 0, 400, 2300))

tableView.tableHeaderView = scrollView
查看更多
Evening l夕情丶
3楼-- · 2019-03-14 09:21

You need to set the frame of your UIScrollView so that it is less than the contentsize. Otherwise, it won't scroll.

Also, I would recommend that you add scroller.contentSize = CGSizeMake(400, 2300) to your viewDidLoad method.

查看更多
Explosion°爆炸
4楼-- · 2019-03-14 09:25

If you use AutoLayout,

Set content size in viewdidAppear which works for me.

override func viewDidAppear(_ animated: Bool) {

    scrollView.contentSize = CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height+300)

}
查看更多
何必那么认真
5楼-- · 2019-03-14 09:30

Alot of the time the code is correct if you have followed a tutorial but what many beginners do not know is that the scrollView is NOT going to scroll normally through the simulator. It is suppose to scroll only when you press down on the mousepad and simultaneously scroll. Many Experienced XCode/Swift/Obj-C users are so use to doing this and so they do not know how it could possibly be overlooked by beginners. Ciao :-)

@IBOutlet weak var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(scrollView)
// Do any additional setup after the view
}

override func viewWillLayoutSubviews(){
super.viewWillLayoutSubviews()
scrollView.contentSize = CGSize(width: 375, height: 800)
}

This code will work perfectly fine as long as you do what I said up above

查看更多
Juvenile、少年°
6楼-- · 2019-03-14 09:37

Swift 3.0 version

scroller.contentSize = CGSize(width: scroller.contentSize.width, height: 2000)
查看更多
家丑人穷心不美
7楼-- · 2019-03-14 09:37

If you are using autolayout, then the contentSize property stops working and it will try to infer the content size from the constraints. If that is the case, then your problem could be that you are not defining the necessary constraints to the content view so that the scrollview can infer the content size. You should define the constraints of your content view to the top and bottom edges of the scrollview.

查看更多
登录 后发表回答