KVO,即:Key-Value Observing,键值观察机制,当指定对象的属性被修改后,对象会接受到通知,然后做相应的变化。
简单的说就是每次指定的被观察对象的属性被修改后,KVO就会自动通知相应的观察者了。
1.指定被观察者的属性,如
//KVO监听字体改变
[_textView addObserver:self forKeyPath:@"font" options:NSKeyValueObservingOptionNew context:nil];
2.实现回调方法,如:
//KVO监听字体的改变
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSString *fontname;
fontname = [change objectForKey:@"new"]; //将新的字体赋给字体名称
_textView.font = [UIFont fontWithName:fontname size:17];
}
3.改变属性,如:
//设置字体
- (void)fontSetting
{
UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:@"设置字体" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"仿宋", @"楷体",@"黑体",@"宋体",@"系统字体",nil];
actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
[actionSheet showInView:self.view];
}
//弹出选择视图,切换字体
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0)
{
_textView.font = [UIFont fontWithName:@"Fangsong" size:17];
}
else if(buttonIndex == 1)
{
_textView.font = [UIFont fontWithName:@"Kaiti" size:17];
}
else if (buttonIndex == 2)
{
_textView.font = [UIFont fontWithName:@"SimHei" size:17];
}
else if (buttonIndex == 3)
{
_textView.font = [UIFont fontWithName:@"SimSun" size:17];
}
else if (buttonIndex == 4)
{
_textView.font = [UIFont fontWithName:@"Helvetica Neue" size:17];
}
}