- 一般以set开头的方法是赋值操作,多次赋值一般会覆盖上一次的操作
- 一般以add开头的方法是添加操作,多次添加一般会累加
- 注意:这里的set开头的方法不包括set方法
以富文本属性作为示例:
#pragma mark ---------- test1-------------
UILabel *label = [[UILabel alloc] init];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"testtest"];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSFontAttributeName] = [UIFont systemFontOfSize:15];
[string setAttributes:dict range:NSMakeRange(0, 2)];
NSMutableDictionary *dict2 = [NSMutableDictionary dictionary];
dict2[NSForegroundColorAttributeName] = [UIColor blueColor];
dict2[NSUnderlineStyleAttributeName] = @YES;
[string setAttributes:dict2 range:NSMakeRange(0, 3)];
用setAttributes设置结果是第二次的操作直接把第一次的操作给覆盖,虽然它们设置的不是同一个内容;
#pragma mark -------- test2-----------------------
UILabel *labelTest = [[UILabel alloc] init];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"1234567"];
NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
dictM[NSFontAttributeName] = [UIFont systemFontOfSize:18];
[attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15] range:NSMakeRange(0, 3)];
[attributedString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:18] range:NSMakeRange(2, 3)];
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor]range:NSMakeRange(0, 4)];
labelTest.attributedText = attributedString;
用addAttribute
方法,结果设置的内容都会起作用;
Objective-C
中很多这样类似的方法规律,再比如UIButton
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
// 会累加
[btn addTarget:self action:@selector(clickBtn) forControlEvents:UIControlEventTouchUpOutside];
[btn addTarget:self action:@selector(clickBtn) forControlEvents:UIControlEventTouchDownRepeat];
// 会覆盖
[btn setTitle:@"111" forState:UIControlStateNormal];
[btn setTitle:@"222" forState:UIControlStateNormal];