美文网首页iOS知多少IOS开发iOS笔记
iOS中以set开头和add开头的方法规律

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

作者: 船长_ | 来源:发表于2015-11-11 10:57 被阅读648次
  • 一般以set开头的方法是赋值操作,多次赋值一般会覆盖上一次的操作
  • 一般以add开头的方法是添加操作,多次添加一般会累加
  • 注意:这里的set开头的方法不包括set方法
    以富文本属性作为示例:
#pragma mark ---------- test1-------------
    UILabel *label = [[UILabel alloc] init];
    label.frame = CGRectMake(100, 200, 200, 50);
    [self.view addSubview:label];
    
    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)];
    
    label.attributedText = string;
  • 用setAttributes设置结果是第二次的操作直接把第一次的操作给覆盖,虽然它们设置的不是同一个内容;
#pragma mark -------- test2-----------------------
    UILabel *labelTest = [[UILabel alloc] init];
    labelTest.frame = CGRectMake(100, 300, 200, 50);
    [self.view addSubview:labelTest];
    
    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方法,结果设置的内容都会起作用;

oc中很多这样类似的方法规律,再比如UIButton

   UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
   btn.frame  = CGRectMake(100,100,100, 50);
   
   // 会累加
   [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];
   
   [self.view addSubview:btn];

相关文章

网友评论

本文标题:iOS中以set开头和add开头的方法规律

本文链接:https://www.haomeiwen.com/subject/xiehhttx.html