Last active
June 11, 2017 13:32
-
-
Save anirudhamahale/b1fb551c9784c2921556e9e9bcaf1335 to your computer and use it in GitHub Desktop.
Populate in UIScrollView.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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