swift pickerView的簡單使用以及模擬無限滾動老虎機(jī)等

先上效果圖:
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)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容