前言
公司新項目采用Swift3.0開發,以前自己用的是OC 封裝的,現在用不了,從github上拉下來的好像不行,都是以前老版本的,還要自己做版本提升,索性自己封裝一個輪播,很多的輪播實現都是基于ScrollView水平添加多個ImageView實現,個人覺的不是很好,因為如果要播放的輪播圖太多的話,這種方法會導致一次性創建多個ImageView,占用內存,所以推薦CollectionView。效果圖如下:
TextKitDemo1.gif
使用說明
一切都在代碼中,創建控件
lazy var tableView = UITableView()
lazy var modelMArr = [YWCycleModel]()
var cycleView : YWCycleView?
override func viewDidLoad() {
super.viewDidLoad()
tableView.frame = view.bounds
tableView.delegate = self
tableView.dataSource = self
view.addSubview(tableView)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
cycleView = YWCycleView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 250))
guard let cycleView = cycleView else {
return
}
cycleView.delegate = self
tableView.tableHeaderView = cycleView
requestData()
}
模擬請求數據:
func requestData() {
let tempArr = [["title":"中國奧運軍團三金回顧","imageUrl":"http://pic33.nipic.com/20130916/3420027_192919547000_2.jpg"],
["title":"《封神傳奇》進世界電影特效榜單?山寨的!","imageUrl":"http://imgstore.cdn.sogou.com/app/a/100540002/503008.png"],
["title":"奧運男子4x100自由泳接力 菲爾普斯","imageUrl":"http://i1.hexunimg.cn/2014-08-15/167580248.jpg"],
["title":"頂住丟金壓力 孫楊晉級200自決賽","imageUrl":"http://pic6.huitu.com/res/20130116/84481_20130116142820494200_1.jpg"]];
for dic in tempArr {
let model = YWCycleModel()
model.imageStr = dic["imageUrl"]
model.title = dic["title"]
modelMArr.append(model)
}
guard let cycleView = cycleView else {
return
}
cycleView.dataArr = modelMArr
}
點擊事件代理回調:
extension ViewController: YWCycleViewDelegate {
func cycleViewDidSelected(cycleView: YWCycleView, selectedIndex: NSInteger) {
print("打印了\(selectedIndex)")
}
}
這樣一個輪播模塊就完成了
結語
只是展示如何使用的代碼,有興趣的同學歡迎去我的github下載相對應的代碼Demo,如果覺得還行,可以放在以后項目中使用。如果代碼哪里有問題,歡迎指教~~~~
ps:因為時間關系,很多屬性來不及封裝,我會在有時間的時候,多封裝幾種樣式的,最后奉上Demo地址:https://github.com/iosyaowei/YWCycleViewDemo