is there a uipickerview delegate method like scrollviewDidScroll?

后端 未结 5 477
情歌与酒
情歌与酒 2020-12-11 05:59

I have a customized UIPickerview and I do not want to use a datepicker. I want to implement the feature where when a user scrolls down/up the hours, the AM/PM component swi

5条回答
  •  自闭症患者
    2020-12-11 06:44

    I just found a way to achieve "pickerDidScroll",it work fine. The key point is add KVO to the row view. Here is my code:

    //picker view delegate
    
    - (UIView*)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    
        if (!view) {
            view = [[RatchetScrollUnit alloc] initWithFrame:CGRectZero];
            //
            [((RatchetScrollUnit*)view) addRatchetObserver:self];
        }
        return view;
    }
    
    //KVO
    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
        if (self.ratchet) {
            NSInteger row = [self.ratchet selectedRowInComponent:0];
    
            if (row != _lastRow) {
                _lastRow = row;
    
                if (self.delegate && [self.delegate respondsToSelector:@selector(ratchetScrollerDidRatchetedToTooth:)]) {
    
                    [self.delegate ratchetScrollerDidRatchetedToTooth:row];
                }
            }
        }
    }
    

    The "RatchetScrollUnit" class :

    @interface RatchetScrollUnit ()
    @property (nonatomic,assign) BOOL observed;
    @property (nonatomic,weak) NSObject *myObserver;
    @end
    
    @implementation RatchetScrollUnit
    
    - (instancetype)initWithFrame:(CGRect)frame {
        self = [super initWithFrame:frame];
    
        if (self) {
            _observed = NO;
            self.backgroundColor = [UIColor clearColor];
        }
        return self;
    }
    
    - (void)dealloc {
        if (self.observed) {
            [self removeObserver:self.myObserver forKeyPath:@"frame" context:nil];
        }
    }
    
    - (void)addRatchetObserver:(NSObject*)observer {
        if (self.observed) {
            return;
        }
        self.observed = YES;
        self.myObserver = observer;
        //
        [self addObserver:observer
               forKeyPath:@"frame"
                  options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew
                  context:nil];
    }
    

    Have a try

提交回复
热议问题