user3246092
user3246092

Reputation: 900

UIScrollView Programmatically in Swift

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()
    }
}

Upvotes: 25

Views: 42533

Answers (2)

Pankaj purohit
Pankaj purohit

Reputation: 485

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)

Upvotes: 10

Samrez Ikram
Samrez Ikram

Reputation: 601

So you should use following line

containerView.userInteractionEnabled = true

Upvotes: 3

Related Questions