iOS 顺传

ios 顺传一层的话,直接用属性 改变里面的值

顺传穿两到三层的话 使用KVO

 

 

// 设置item

- (void)setItem:(UITabBarItem *)item

{

    _item = item;

    

    // KVO 监听属性改变

    [item addObserver:self forKeyPath:@"badgeValue" options:0 context:nil];

    [item addObserver:self forKeyPath:@"title" options:0 context:nil];

    [item addObserver:self forKeyPath:@"image" options:0 context:nil];

    [item addObserver:self forKeyPath:@"selectedImage" options:0 context:nil];

    

    [self observeValueForKeyPath:nil ofObject:nil change:nil context:nil];

}

 

- (void)dealloc

{

    [self.item removeObserver:self forKeyPath:@"badgeValue"];

    [self.item removeObserver:self forKeyPath:@"title"];

    [self.item removeObserver:self forKeyPath:@"image"];

    [self.item removeObserver:self forKeyPath:@"selectedImage"];

}

 

/**

 *  监听到某个对象的属性改变了,就会调用

 *

 *  @param keyPath 属性名

 *  @param object  哪个对象的属性被改变

 *  @param change  属性发生的改变

 */

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context

{

    // 设置文字

    [self setTitle:self.item.title forState:UIControlStateSelected];

    [self setTitle:self.item.title forState:UIControlStateNormal];

    

    // 设置图片

    [self setImage:self.item.image forState:UIControlStateNormal];

    [self setImage:self.item.selectedImage forState:UIControlStateSelected];

    

    // 设置提醒数字

    self.badgeButton.badgeValue = self.item.badgeValue;

    

    // 设置提醒数字的位置

    CGFloat badgeY = 5;

    CGFloat badgeX = self.frame.size.width - self.badgeButton.frame.size.width - 10;

    CGRect badgeF = self.badgeButton.frame;

    badgeF.origin.x = badgeX;

    badgeF.origin.y = badgeY;

    self.badgeButton.frame = badgeF;

}

你可能感兴趣的:(iOS 顺传)