2017-06-16 79 views
-3

我想在swift 3中實現自動滾動到UIScrollView。任何人都可以幫助我。如何使用Swift 3在UIScrollview中實現自動滾動?

其實我是iOS開發新手。

我的代碼:

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) 
} 

由於提前

+1

add more detai LS。 – Maddy

+0

看到答案,你可以使用自動滾動計時器 – Dhiru

+0

' bannerscView.addSubview(bannerImg)'爲什麼你每次加入SubView時間間隔? – Dhiru

回答

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

謝謝巴厘島,爲您的快速回復:) –

0

自動滾動,滾動型?嗯......

沒有填寫滾動型根本就不是Possible.Either 您使用自動佈局或編程做鑑於contentSize

但你可以更新基於其包含的子視圖就像一個UIScrollView的內容大小下面

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

謝謝DS Dharma爲你的快速回復:) –

0

啓動計時器,當你要開始自動滾動

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

滾動了滾動後每兩秒

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) 
} 
    } 
} 
+0

非常感謝你,Dhiru的寶貴回覆。它的工作 –