I've been unable to find a way of accurately enabling horizontal and vertical scrolling programmatically with Swift (my objects are programmatic thus making using auto layout in IB unfeasible).
The tutorial I followed allows for scrolling both ways as intended. The problem is my button stays in the same spot occupying part of the screen no matter where you scroll. I've had this same result with another tutorial and am quite confused as to why this is happening.
I haven't been able to find an answer to this so I'm assuming some others will find this beneficial.
Here is the code I have. I made a very basic project based on this tutorial: http://koreyhinton.com/blog/uiscrollview-crud.html
class ViewController: UIViewController, UIScrollViewDelegate {
var scrollView: UIScrollView!
var containerView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
let buttonOne = UIButton.buttonWithType(UIButtonType.System) as UIButton
buttonOne.frame = CGRectMake(10, 50, 50, 50)
buttonOne.backgroundColor = UIColor.greenColor()
buttonOne.setTitle("test", forState: UIControlState.Normal)
buttonOne.addTarget(self, action: "buttonAction1x1:", forControlEvents: UIControlEvents.TouchUpInside)
self.scrollView = UIScrollView()
self.scrollView.delegate = self
self.scrollView.contentSize = CGSizeMake(1000, 1000)
containerView = UIView()
scrollView.addSubview(containerView)
view.addSubview(scrollView)
self.view.addSubview(buttonOne)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollView.frame = view.bounds
containerView.frame = CGRectMake(0, 0, scrollView.contentSize.width, scrollView.contentSize.height)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
If you want to programmatically make SwiftUI's ScrollView move to a specific location, you should embed a ScrollViewReader inside it. This provides a scrollTo() method that can move to any view inside the parent scrollview, just by providing its anchor.
To fix ScrollView Not scrolling with React Native, we wrap the content of the ScrollView with the ScrollView. to wrap ScrollView around the Text components that we render inside. Anything inside the ScrollView will scroll. As a result, we should see text inside and we can scroll up and down.
Your code is working perfectly, but there is a small problem in adding buttonOne on the view.
You have added buttonOne on self.view (i.e subview of self.view), not containerView which is on scrollView.
You should use the following code
containerView.addSubview(buttonOne)
instead of
self.view.addSubview(buttonOne)
So you should use following line
containerView.userInteractionEnabled = true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With