Search code examples
iosswift3uiscrollviewhorizontalscrollview

Adding images to horizontal paging UIScrollView


I'm trying to create a new user onboarding horizontal scroll view for an app in Swift 3.0.

I've managed to build out a set of 4 slides with page controls and a scroll view, with a very simple xib including a label, such that I can get my pages to scroll (across 4 slides) with a how-to step on each slide.

My code is below - as you can see with each slide the text is changing.

Now, I want to add images to these slides. I've added UIImageView to the xib, but I am not sure how to add them to the array that I've created here. Does anyone have advice? Thanks!

func createSlides() -> [Slide] {
    let slide1:Slide = Bundle.main.loadNibNamed("Slide", owner: self, option: nil)?.first as! Slide
    slide1.label1.text = "Welcome to app!"

    let slide2:Slide = Bundle.main.loadNibNamed("Slide", owner: self, options: nil)?.first as! Slide
    slide2.label1.text = "Browse for items"

    let slide3:Slide = Bundle.main.loadNibNamed("Slide", owner: self, options: nil)?.first as! Slide
    slide3.label1.text = "Save your favorites"

    let slide4:Slide = Bundle.main.loadNibNamed("Slide", owner: self, options: nil)?.first as! Slide
    slide4.label1.text = "Share with friends"

return [slide1,slide2,slide3,slide4]

}

Solution

  • The same way you are setting label1.text.

    First, you need to be sure your UIImageView object is linked to an IBOutlet, so you can access it via code. I'm assuming you already know how to do it, since you are access label1 already.

    Afterwards, just instantiate your UIImage like this:

    slide1.imageView.image = UIImage(named: "tutorial1")
    

    I hope it helps.