How to implement auto scroll in UIScrollview using

2019-09-22 00:31发布

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

标签: ios swift3
4条回答
仙女界的扛把子
2楼-- · 2019-09-22 00:32

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)
}
    }
}
查看更多
一夜七次
3楼-- · 2019-09-22 00:34

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
查看更多
SAY GOODBYE
4楼-- · 2019-09-22 00:45
scroll.setContentOffset(CGPoint(x: xPos, y: yPos), animated: true)
查看更多
放我归山
5楼-- · 2019-09-22 00:46

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
        }
    }
}
查看更多
登录 后发表回答