1.懶加載scrollview
//懶加載scrollview
lazy var scrollView:UIScrollView = {
let tempScrollView = UIScrollView(frame: CGRectMake(0,0,UIScreen.mainScreen().bounds.size.width,150))
tempScrollView.contentSize = CGSizeMake(6 * screenWidth,150)
tempScrollView.pagingEnabled = true
tempScrollView.delegate = self
tempScrollView.bounces = false
tempScrollView.showsHorizontalScrollIndicator = false
return tempScrollView
}()```
2.通過網(wǎng)絡(luò)數(shù)據(jù)請(qǐng)求的數(shù)據(jù)給輪播圖加載圖片
private func addScrollView() {
NetWorkTool.shareNetWorkTool.httpRequest(.GET, urlString: Macro.homePageHeaderURL, parameter: nil) {(respondeData, error) -> () in
guard let receiveObject = respondeData else{
print("輪播圖error\(error)")
return
}
var imageArray = [String]()
for dict in receiveObject["pic"] as! [[String:AnyObject]]{
imageArray.append(dict["randpic_iphone6"]! as! String)
}
//輪播圖,最后一張作為假圖橡娄,跟第0張一模一樣
//0 1 2 3 4 0
imageArray.append(imageArray[0])
// 遍歷數(shù)組創(chuàng)建UIImageView并且添加到scrollView上面
for (index,value) in imageArray.enumerate(){
let imageView = UIImageView(frame: CGRectMake(CGFloat(index)*screenWidth, 0, screenWidth, 150))
imageView.sd_setImageWithURL(NSURL(string: value))
self.scrollView.addSubview(imageView)
}
self.tableView.tableHeaderView = self.scrollView
}
}
3.設(shè)置一個(gè)定時(shí)器,和定時(shí)器觸發(fā)的方法
NSTimer.scheduledTimerWithTimeInterval(3.5, target: self, selector:"turnToNext", userInfo: nil, repeats: true)
4.定時(shí)器觸發(fā)的方法,是圖片實(shí)現(xiàn)輪播
func turnToNext(){
let index = scrollView.contentOffset.x/screenWidth
scrollView.setContentOffset(CGPointMake((index+1)*screenWidth, 0), animated: true)
}