UIPickerView: Get row value while spinning?

2019-01-20 11:16发布

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 subclassing UIPickerView then overriding the mouseDown method, but I couldn't get this to work. Any suggestions would be very much appreciated.

3条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-20 11:37

The UIPickerView dimensions are fairly consistent. Instead of subclassing it, perhaps you could overlay a UIView of your own on top of the picker view, from which you can track and measure dragging motions, before passing those touches down to the picker view.

查看更多
Anthone
3楼-- · 2019-01-20 11:38

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
    }
}
查看更多
不美不萌又怎样
4楼-- · 2019-01-20 11:44

Perhaps try implementing the delegate method:

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view

You could treat it as a passthrough (just passing back the reusingView parameter) but each time it was called you would know that view was coming on the screen as the user scrolled - then you could calculate how many views offset from this one the center view was.

查看更多
登录 后发表回答