UIPickerView: Get row value while spinning?

前端 未结 3 671
醉话见心
醉话见心 2020-12-11 17:13

I\'d like to get the row value in real-time as the iPhone user spins a wheel in a UIPickerView (not just when the wheel settles onto a particular row). I looked into subclas

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-11 18:16

    You can find UIScrollView in UIPickerView hierarchy by the following method:

    func findScrollView(view:UIView) -> UIScrollView? {
        if view is UIScrollView {
            return view as? UIScrollView
        }
        for subview in view.subviews {
            if subview is UIView {
                let result = findScrollView(subview as UIView)
                if result != nil {
                    return result
                }
            }
        }
        return nil
    }
    

    Implement and setup UIScrollViewDelegate:

    let scrollView = findScrollView(pickerView)
    if scrollView != nil {
        scrollView!.delegate = self
    }
    

    And detect current selected item:

    func scrollViewDidScroll(scrollView: UIScrollView) {
        let offset = scrollView.contentOffset.y
        let index = Int(offset/itemHeight)
        if index >= 0 && index < items.count {
            let item = items[index]
            // do something with item
        }
    }
    

提交回复
热议问题