ScrollView populate UIViews using .xib problem

I am trying to create a scrollView that populates a number of Views so the user can scroll through the views. The view is xib file and loaded to the scrollview but I can’t make copies of it.

I guess is something simple but I can’t figure it out.

1)I can create a new UIView though the for loop and I am trying to add the customView as a subview but it only adds on the last added view in the scroll view.( I am not sure if this is the efficient way to do this )

  1. trying to make copies didn’t work because I can’t modify each view. everything is a copy of the same one and then single change change ALL OF THEM

extension UIView{
func copyView() -> UIView{
return (NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self)) as? UIView)!
}
}

3)If there is a better way to do this without add a new view and subviews Instead just make copies of customView it would be perfect.

import UIKit

class ScrollTableViewCell: UITableViewCell {

@IBOutlet weak var scrollView: UIScrollView!

let customView:ViewForScrollView = (Bundle.main.loadNibNamed("ViewForScrollView", owner: self, options: nil)!.first as? ViewForScrollView)!

override func awakeFromNib() {
    super.awakeFromNib()
    
    self.scrollView.delegate = self
    tileView(weatherHours: 4)
   
    
}


override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

func tileView(weatherHours : Int){
    let tileWidth : CGFloat = 60
    let tileHeight : CGFloat = 60
    let marginX : CGFloat = 15
    let viewOriginX : CGFloat = 15
    let viewOriginY : CGFloat = 5
    var padding : CGFloat = 0
    
    for (index) in 1...weatherHours{
        
        customView.label.text = "\(index)"
        let aView = UIView()
        aView.backgroundColor = UIColor.red
        aView.addSubview(customView)

// let addView = customView.copyView()
// let copyLabel = addView.subviews[0] as! UILabel
// copyLabel.text = “0”
aView.frame = CGRect(x: padding + marginX, y: viewOriginY, width: tileWidth , height: tileHeight)
padding = padding + tileWidth + 15
scrollView.addSubview(aView)

    }
    let scrollViewWidth : CGFloat = tileWidth + (padding) + 15
    scrollView.contentSize = CGSize(width: scrollViewWidth , height: 80)
}

}

extension ScrollTableViewCell : UIScrollViewDelegate{

}

extension UIView{
func copyView() -> UIView{
return (NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self)) as? UIView)!
}
}

Hi @scy

You are adding the same view over and over again in your for loop. Your code should look something like this:

for (index) in 1...weatherHours{
    let customView:ViewForScrollView = (Bundle.main.loadNibNamed("ViewForScrollView", owner: self, options: nil)!.first as? ViewForScrollView)!
    customView.label.text = "\(index)"
   ....
}

Nikita

1 Like