
QQ20180914-145457.gif
所謂的無限滾動就是把component里的Row設(shè)置的足夠多
在這確定鍵是暫停計時器以及滾動,取消鍵是繼續(xù)計時器
1.完成如下視圖布局

image.png
2.為picker添加代理和數(shù)據(jù)源協(xié)議
picker.dataSource = self
picker.delegate = self
//父視圖繼承相關(guān)代理UIPickerViewDelegate,UIPicke rViewDataSource
//設(shè)置測試數(shù)據(jù)(我用的二維數(shù)組)
let items = [["a1","a2","a3","a4"],["a1","a2"],["a1","a2","a3"]]
3.完成相關(guān)代理方法
// 是否循環(huán)滾動
let isCircularly = true
//picker有幾組
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return items.count
}
//每組有多少個
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
for (index,item) in items.enumerated() {
if component == index{
if isCircularly{
return item.count * 1000
}else{
return item.count
}
}
}
return 0
}
//每個顯示的內(nèi)容
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if isCircularly{
return items[component][row % items[component].count]
}else{
return items[component][row]
}
}
這樣就可以顯示并且無限滑動了
4.老虎機(jī)自動滾動
//添加計時器
var time:Timer!
time = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(timer), userInfo: nil, repeats: true)
time.fire()
//滾動相關(guān)代碼
@objc func timer() {
for index in 0..<items.count {
var temp = picker.selectedRow(inComponent: index)
temp -= 1
picker.selectRow(temp, inComponent: index, animated: true)
}
}
//為確定鍵添加點擊事件
@objc func clickSure(){
//暫停計時器
time.fireDate = Date.distantFuture
for index in 0..<items.count {
//打印選中的Row的索引
if isCircularly{
print((picker.selectedRow(inComponent: index))%items[index].count)
}else{
print(picker.selectedRow(inComponent: index))
}
}
}
//為取消鍵添加點擊事件
@objc func clickCancle() {
time.fireDate = Date.distantPast
}
如果要使各個列滾動方向不同,可以在time()方法里面添加隨機(jī)事件(+= 或者 -=)
相關(guān)計時器的簡單用法請看:http://www.itdecent.cn/p/185eadc38ff0
git庫:https://github.com/Liushaungxi/LearnSwift(List4)