How to update ScrollView Width after device rotation? - swift

I am following a tutorial to create a swift app that adds a number of views to a scroll view and then allows me to scroll between them. I have the app working and understand it for the most part. When I change the orientation of the device the views width don't get updated so I have parts of more than one view controller on the screen? Does anybody know how to fix this? From my understanding I need to call something in the viewsDidTransition method to redraw the views. Any help would be greatly appreciated. Thanks!
Here is what I have so far:
import UIKit
class ViewController: UIViewController {
private let scrollView = UIScrollView()
private let pageControl: UIPageControl = {
let pageControl = UIPageControl()
pageControl.numberOfPages = 5
pageControl.backgroundColor = .systemBlue
return pageControl
}()
override func viewDidLoad() {
super.viewDidLoad()
scrollView.delegate = self
pageControl.addTarget(self,
action: #selector(pageControlDidChange(_:)),
for: .valueChanged)
scrollView.backgroundColor = .red
view.addSubview(scrollView)
view.addSubview(pageControl)
}
#objc private func pageControlDidChange(_ sender: UIPageControl){
let current = sender.currentPage
scrollView.setContentOffset(CGPoint(x: CGFloat(current) * view.frame.size.width,
y: 0), animated: true)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
pageControl.frame = CGRect(x: 10, y: view.frame.size.height - 100, width: view.frame.size.width - 20, height: 70)
scrollView.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height - 100)
if scrollView.subviews.count == 2 {
configureScrollView()
}
}
private func configureScrollView(){
scrollView.contentSize = CGSize(width: view.frame.size.width*5, height: scrollView.frame.size.height)
scrollView.isPagingEnabled = true
let colors: [UIColor] = [.systemRed, .systemGray, .systemGreen, .systemOrange, .systemPurple]
for x in 0..<5{
let page = UIView(frame: CGRect(x: CGFloat(x) * view.frame.size.width, y: 0, width: view.frame.size.width, height: scrollView.frame.size.height))
page.backgroundColor = colors[x]
scrollView.addSubview(page)
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
print("hello world")
}
}
extension ViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
pageControl.currentPage = Int(floorf(Float(scrollView.contentOffset.x) / Float(scrollView.frame.size.width)))
}
}

Related

UIScrollView with paging enable not working properly

Trying to add four UIView's in UIScrollView
The issue is next (2, 3, and 4) view gets a bit off from the visible screen view when scroll.
override init(frame: CGRect) {
super.init(frame: frame)
configureSlider()
}
private func configureSlider() {
Bundle.main.loadNibNamed("CarouselSliderView", owner: self, options: nil)
addSubview(contentView)
for i in 0...3 {
let view = UIView()
switch i {
case 0:
view.backgroundColor = .brown
case 1:
view.backgroundColor = .yellow
case 2:
view.backgroundColor = .green
case 3:
view.backgroundColor = .blue
default:
view.backgroundColor = .red
}
slides.append(view)
}
setupSlideScrollView(slides: slides)
pageControl.numberOfPages = slides.count
pageControl.currentPage = 0
self.bringSubviewToFront(pageControl)
}
set each UIView frames:
private func setupSlideScrollView(slides : [UIView]) {
let screenRect = UIScreen.main.bounds
let screenWidth = screenRect.size.width
for i in 0 ..< slides.count {
slides[i].frame = CGRect(x: screenWidth * CGFloat(i), y: 0, width: screenWidth, height: self.frame.height)
topScrollView.addSubview(slides[i])
}
topScrollView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: self.frame.height)
topScrollView.contentSize = CGSize(width: screenWidth * CGFloat(slides.count), height: self.frame.height)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let pageIndex = round(scrollView.contentOffset.x/self.frame.width)
pageControl.currentPage = Int(pageIndex)
}

How to add a Label for Each Image in the iCarousel View Framework

I have used the iCarousel Framework in my View Controller. But, I am not sure how can I add a label below each image while scrolling in the carousel view. Would appreciate your help! Thanks!
func numberOfItems(in carousel: iCarousel) -> Int {
return 10
}
func carousel(_ carousel: iCarousel, viewForItemAt index: Int, reusing view: UIView?) -> UIView {
let view = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width/1.4, height: 300))
view.backgroundColor = .red
let imageview = UIImageView(frame: view.bounds)
view.addSubview(imageview)
imageview.contentMode = .scaleToFill
imageview.image = UIImage(named: "Dog_\(index+1)")
return view
}
func carouselDidEndScrollingAnimation() {
if (myCarousel.currentItemIndex == 1) {
dogNameLabel.text = "Brownie!"
}
}
let myCarousel: iCarousel = {
let view = iCarousel()
view.type = .rotary
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(myCarousel)
myCarousel.dataSource = self
myCarousel.frame = CGRect(x: 0, y: 220, width: view.frame.size.width, height: 400)
}
There are too many option. You can create custom view (xib) for reusability. You need to label in contentView above imageView.
But you need to create view like that.
func carousel(_ carousel: iCarousel, viewForItemAt index: Int, reusing view: UIView?) -> UIView {
let view = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width/1.4, height: 300))
view.backgroundColor = .red
let imageview = UIImageView(frame: view.bounds)
view.addSubview(imageview)
imageview.contentMode = .scaleToFill
imageview.image = UIImage(named: "Dog_\(index+1)")
let label = UILabel()
label.text = "Enter your text"
label.frame = CGRect(x: 0, y: 20, width: view.frame.size.width, height: 30)
//or use constraints
view.addSubview(label)
return view
}

ScrollView doesn't scroll swift

I have one method that shows a photo and zooms in it if the user wants. I used a scroll view so that the user could scroll if he zooms in a photo. My zoom works but it zoom into the top left corner and my scroll view doesn't scroll anywhere else even though it shows vertical and horizontal bars responsible for scroll moving.
class ImageViewController: UIViewController, UIScrollViewDelegate {
var myscrollView: UIScrollView!
var imgView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
myscrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height))
self.view.addSubview(myscrollView)
myscrollView.delegate = self
// myscrollView.scrollRectToVisible(CGRect(x: 100, y: 100, width: 1, height: 1), animated: true)
// myscrollView.setContentOffset(CGPoint(x: 0, y: view.frame.size.height), animated: true)
// myscrollView.contentSize = CGSize(width: view.frame.width, height: view.frame.height)
print("\(myscrollView.frame.height) \(myscrollView.frame.width)")
//myscrollView.contentSize = CGSize(width: 1000, height: 2000)
myscrollView.isScrollEnabled = true
myscrollView.minimumZoomScale = 1.0
myscrollView.maximumZoomScale = 10.0//maximum zoom scale you want
myscrollView.zoomScale = 1.0
myscrollView.alwaysBounceVertical = false
myscrollView.alwaysBounceHorizontal = false
myscrollView.showsVerticalScrollIndicator = true
myscrollView.flashScrollIndicators()
// scrollView.isPagingEnabled = false
// self.scrollView.contentSize = self.view.frame.size * 2//or what ever size you want to set
// myscrollView.contentOffset = CGPointMake((myscrollView.contentSize.width-myscrollView.frame.size.width)*.5f, .0f);//scroll to center
// myscrollView.contentOffset = CGPoint((myscrollView.contentSize.width-myscrollView.frame.size.width)*.5f, .0f)
myscrollView.addSubview(imgView)
//self.view.addSubview(imgView)
imgView!.layer.cornerRadius = 11.0
imgView.bounds = myscrollView.bounds
//imgView!.clipsToBounds = false
imgView.isUserInteractionEnabled = true
imgView.heightAnchor.constraint(equalToConstant: 50).isActive = true
// imgView.widthAnchor.constraint(equalToConstant: 50).isActive = true
imgView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 64).isActive = true
imgView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: 0).isActive = true
imgView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
// imgView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
imgView.translatesAutoresizingMaskIntoConstraints = false
myscrollView.contentSize = CGSize(width: imgView.frame.width , height: 2000)
// myscrollView.contentSize = imgView.bounds.size
// Do any additional setup after loading the view.
}
// func scrollViewDidZoom(_ scrollView: UIScrollView) {
// var offsetY: CGFloat!
// offsetY = 0;
// if (scrollView.zoomScale > 1){
// offsetY = CGFloat(scrollView.contentOffset.y);
// }
// //CGPoint(x: scrollView.contentOffset.x, y: offsetY)
// scrollView.setContentOffset(CGPoint(x:
// scrollView.contentOffset.x, y: offsetY), animated: true)
//
// // [aScrollView setContentOffset:
// CGPointMake(aScrollView.contentOffset.x, offsetY)];
//
// }
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imgView
}
// override func viewDidLayoutSubviews() {
// myscrollView.delegate = self
// myscrollView.contentSize =
//CGSize(width:self.view.frame.size.width, height: 1000)
// }
// func viewForZooming(in scrollView: UIScrollView) -> UIView? {
// return imgView
// }
}
I tried to set contentSize manually to some big or small values and well as using frame.width and height but none of them seem to be working. Can someone please help what is my problem? Thanks in advance :)
Just try these lines of code and check, What are you missing-
let screenSize: CGRect = UIScreen.main.bounds
let scrollView = UIScrollView()
override func viewDidLoad() {
super.viewDidLoad()
scrollView.contentSize = CGSize(width: screenSize.width, height: 1300)
scrollView.frame = CGRect(x: 0, y: 70, width: screenSize.width, height: screenSize.height-70)
scrollView.backgroundColor = UIColor.clear
view.addSubview(scrollView)
}
Try implementing scrollViewDidZoom method as follows;
func scrollViewDidZoom(_ scrollView: UIScrollView) {
let offsetX = max((scrollView.bounds.size.width-scrollView.contentSize.width) * 0.5, 0.0)
let offsetY = max((scrollView.bounds.size.height-scrollView.contentSize.height) * 0.5, 0.0)
self.scrollView.contentInset = UIEdgeInsetsMake(offsetY, offsetX, 0, 0)
}

Event scrolling (scrollViewDidScroll) never called - Swift 3

I would like to detect when the user scroll, I used a UIScrollView, I implemented the UIScrollViewDelegate in my ViewController and tried scrollViewDidScroll, scrollViewDidEndScrollingAnimation and all the others but these events are never called.
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate {
#IBOutlet weak var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
let xOrigin = self.view.frame.width
let view1 = View1(frame: CGRect(x: 0, y: 0, width:self.view.frame.width, height: self.view.frame.height))
let view2 = View2(frame: CGRect(x: xOrigin, y: 0, width: self.view.frame.width, height: self.view.frame.height))
let view3 = View3(frame: CGRect(x: xOrigin * 2, y: 0, width: self.view.frame.width, height: self.view.frame.height))
scrollView.addSubview(view1)
scrollView.addSubview(view2)
scrollView.addSubview(view3)
self.scrollView.contentSize = CGSize(width: self.view.frame.width * 3, height: self.view.frame.height)
// hide the scrol bar.
scrollView?.showsHorizontalScrollIndicator = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
print("end scroll")
}
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
print("end scroll")
}
}
You just have to add the delegate to your viewDidLoad() func:
override func viewDidLoad() {
super.viewDidLoad()
//add this line
self.scrollView.delegate = self
}

UISwipeGestureRecognizer not recognized when added to UIView's subviews

I currently have a subclass of UIView which contains numerous subviews. I wish to add a UISwipeGesture to the subviews but unfortunately the swipe gesture is not recognized. I've set userInteractionEnabled = true and direction of the swipe gesture but nothing works.
public class CardStackView: UIView{
public var dataSource = [UIImage]()
private var swipeGuesture: UISwipeGestureRecognizer!
override public func layoutSubviews() {
for img in dataSource{
let view = AppView(image: img, frame: self.frame)
self.addSubview(view)
}
animateSubview()
self.userInteractionEnabled = true
}
func animateSubview(){
for (index, sView) in self.subviews.enumerate() {
swipeGuesture = UISwipeGestureRecognizer(target: self, action: #selector(self.swipeGuestureDidSwipeRight(_:)))
swipeGuesture.direction = .Right
sView.addGestureRecognizer(swipeGuesture)
sView.userInteractionEnabled = true
let move: CGFloat = CGFloat(-20 + index * 20)
let opacity = Float(1 - 0.2 * CGFloat(index))
sView.shadowOpacity(opacity).shadowOffset(CGSizeMake(20 - CGFloat(index) * 5, 20 - CGFloat(index) * 5)).shadowRadius(5).moveX(-move).moveY(-move).gravity().shadowColor(UIColor.grayColor()).duration(1)
.completion({
}).animate()
}
}
func swipeGuestureDidSwipeRight(gesture: UISwipeGestureRecognizer) {
print("Swiped right")
let subview = self.subviews[0]
subview.moveX(-60).duration(1).animate()
}
}
Example
class ExampleController: UIViewController {
var stackView: CardStackView!
override func viewDidLoad() {
super.viewDidLoad()
stackView = CardStackView(frame: CGRect(x: 20, y: 80, width: 200, height: 200))
stackView.dataSource = [UIImage(named: "2008")!, UIImage(named: "2008")!]
self.view.addSubview(stackView)
}
}
self.view.bringSubviewToFront(yourSubview)
try this code for all your subviews and if it doesn't work try this in your controller class for your CardStackView.
Try to call setNeedsLayout for stackView:
override func viewDidLoad() {
super.viewDidLoad()
stackView = CardStackView(frame: CGRect(x: 20, y: 80, width: 200, height: 200))
stackView.dataSource = [UIImage(named: "2008")!, UIImage(named: "2008")!]
stackView.setNeedsLayout()
self.view.addSubview(stackView)
}