iOS中以set开头和add开头的方法规律

  • 一般以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];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容