1、在自定义tabBar中,往tabBar中添加按钮的时候,默认情况下会在按钮的前面和后面添加UITabBarBackgroundView和UIImageView,导致子控件会增加两个,在自动布局中就会出现排版错误。
解决办法:让自定义的tabBar继承UIView。
2、对于tabBarItem,要想改变对象的某个属性,最好使用KVO来监听属性改变,使用的方法如下:
/**
* 监听到某个对象的属行改变了就去调用
*
* @param keyPath 属性名
* @param object 那个对象的属性被改变
* @param change 属性发生的改变
*/
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
使用过程分为三步:
①先监听属性改变:
// 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)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方法:
-(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被销毁时,还会调用监听方法,导致程序奔溃!