1、在自定义tabBar中,往tabBar中添加按钮的时候,默认情况下会在按钮的前面和后面添加UITabBarBackgroundView和UIImageView,导致子控件会增加两个,在自动布局中就会出现排版错误。
1
2
3
4
5
6
7
8
9 |
/** * 监听到某个对象的属行改变了就去调用 * * @param keyPath 属性名 * @param object 那个对象的属性被改变 * @param change 属性发生的改变 */ - ( void )observeValueForKeyPath:(NSString *)keyPath ofObject:(id) object
change:(NSDictionary *)change context:( void
*)context |
使用过程分为三步:
①先监听属性改变:
1
2
3
4
5 |
// 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]; |
②调用监听方法
1
2 |
[self observeValueForKeyPath:nil ofObject:nil change:nil context:nil]; |
③在方法中具体实现属性改变
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33 |
-( void )observeValueForKeyPath:(NSString *)keyPath ofObject:(id) object
change:(NSDictionary *)change context:( void
*)context { // 文字 [self setTitle:self.item.title forState:UIControlStateNormal ]; // 图片 [self setImage:self.item.image forState:UIControlStateNormal]; [self setImage:self.item.selectedImage forState:UIControlStateSelected]; // 设置提醒数字 if
(self.item.badgeValue) { self.badgeButton.hidden = NO; // 设置文字 [self.badgeButton setTitle:self.item.badgeValue forState:UIControlStateNormal]; // 设置尺寸 CGFloat badgeButtonY = 5; CGFloat badgeButtonH =self. badgeButton.currentBackgroundImage.size.height; CGFloat badgeButtonW = self.badgeButton.currentBackgroundImage.size.width; if
(self.item.badgeValue.length >1) { CGSize badgeSize = [self.item.badgeValue sizeWithFont:self.badgeButton.titleLabel.font]; badgeButtonW = badgeSize.width + 10; } CGFloat badgeButtonX = self.frame.size.width - badgeButtonW -10; self. badgeButton.frame = CGRectMake(badgeButtonX, badgeButtonY, badgeButtonW, badgeButtonH); } else { self.badgeButton.hidden = YES; } } |
注意,使用KVC需要释放内存,调用dealloc方法:
1
2
3
4
5
6
7 |
-( 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" ]; } |
如果不将item从self 中移除监听,当self被销毁时,还会调用监听方法,导致程序奔溃!
自定义tabBar中的注意事项,布布扣,bubuko.com
原文地址:http://www.cnblogs.com/angongIT/p/3773874.html