How to implement auto scroll in UIScrollview using Swift 3?

∥☆過路亽.° 提交于 2019-12-13 23:08:09

问题


I want to implement auto scroll to UIScrollView in swift 3. Could any one help me.

Actually I am new in iOS development.

My Code :

var bannerscView: UIScrollView!
 bannerscView = UIScrollView(frame: CGRect(x: 0, y: 50, width: Int(view.bounds.width), height: 350))
    bannerscView.showsVerticalScrollIndicator = true
    view.addSubview(bannerscView)
    bannerscView.backgroundColor = UIColor.red
    bannerscView.translatesAutoresizingMaskIntoConstraints = false

    _ = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(bannerImgScroll), userInfo: nil, repeats: true)

func bannerImgScroll(){


    var xBannerOffset:CGFloat = 5
    for k in 0 ... 5 {

        let bannerImg = UIButton()
        bannerImg.tag = k
        bannerImg.backgroundColor = UIColor.blue //UIColor.darkGray
        bannerImg.setTitle("\(k)", for: .normal)
        //button.addTarget(self, action: #selector(btnTouch), for: UIControlEvents.touchUpInside)

        bannerImg.frame = CGRect(x: xBannerOffset, y: CGFloat(buttonPadding), width: 400, height: 300)
        xBannerOffset = xBannerOffset + CGFloat(buttonPadding) + bannerImg.frame.size.width
        // print("xOffset After : \(xOffset)")
        bannerscView.addSubview(bannerImg)


    }

    bannerscView.contentSize = CGSize(width: xBannerOffset, height: bannerscView.frame.height)
}

Thanks in Advance


回答1:


Start Timer in when you want to start autoScrolling

timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)

Scroll the scrollView after every two second

 func timerAction() {
        yOffSet += 10;
         dispatch_async(dispatch_get_main_queue()) {
  UIView.animateWithDuration(1, delay: 0, options: UIViewAnimationOptions.CurveLinear, animations: {
    self.scrollView.contentOffset.y = yOffSet
    }, completion: nil)
}
    }
}



回答2:


scroll.setContentOffset(CGPoint(x: xPos, y: yPos), animated: true)



回答3:


Auto scroll in ScrollView ? Hmm...

Without filling contentSize of ScrollView simply not Possible.Either your doing in View using autolayout or Programmatically.

But you can update the content size of a UIScrollView based on its contained subviews like below

var contentRect = CGRectZero
for view in self.scrollView.subviews {
    contentRect = CGRectUnion(contentRect, view.frame)
}
self.scrollView.contentSize = contentRect.size



回答4:


Swift 4.x

var yOffset: CGFloat = 0

@objc func timerAction() {

    yOffset += 10

    DispatchQueue.main.async {
        UIView.animate(withDuration: 1.0) {
            self.scrollView.contentOffset.y = self.yOffset
        }
    }
}


来源:https://stackoverflow.com/questions/44585590/how-to-implement-auto-scroll-in-uiscrollview-using-swift-3

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!