Skip to content

Instantly share code, notes, and snippets.

@anirudhamahale
Last active June 11, 2017 13:32
Show Gist options
  • Save anirudhamahale/b1fb551c9784c2921556e9e9bcaf1335 to your computer and use it in GitHub Desktop.
Save anirudhamahale/b1fb551c9784c2921556e9e9bcaf1335 to your computer and use it in GitHub Desktop.
Populate in UIScrollView.
//add all images to the list
func setupList() {
for i in herbs.indices {
//create image view
let imageView = UIImageView(image: UIImage(named: herbs[i].image))
imageView.tag = i
imageView.contentMode = .scaleAspectFill
imageView.isUserInteractionEnabled = true
imageView.layer.cornerRadius = 20.0
imageView.layer.masksToBounds = true
listView.addSubview(imageView)
//attach tap detector
imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didTapImageView)))
}
listView.backgroundColor = UIColor.clear
positionListItems()
}
//position all images inside the list
func positionListItems() {
let listHeight = listView.frame.height
let itemHeight: CGFloat = listHeight * 1.33
let aspectRatio = UIScreen.main.bounds.height / UIScreen.main.bounds.width
let itemWidth: CGFloat = itemHeight / aspectRatio
let horizontalPadding: CGFloat = 10.0
for i in herbs.indices {
let imageView = listView.viewWithTag(i) as! UIImageView
imageView.frame = CGRect(
x: CGFloat(i) * itemWidth + CGFloat(i+1) * horizontalPadding, y: 0.0,
width: itemWidth, height: itemHeight)
}
listView.contentSize = CGSize(
width: CGFloat(herbs.count) * (itemWidth + horizontalPadding) + horizontalPadding,
height: 0)
}
//MARK: Actions
func didTapImageView(_ tap: UITapGestureRecognizer) {
selectedImage = tap.view as? UIImageView
let index = tap.view!.tag
let selectedHerb = herbs[index]
//present details view controller
let herbDetails = storyboard!.instantiateViewController(withIdentifier: "HerbDetailsViewController") as! HerbDetailsViewController
herbDetails.herb = selectedHerb
present(herbDetails, animated: true, completion: nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment