对UIButton 的新的认识 -- 标签的实现

2016-12-07  本文已影响20人  努力奔跑的小男孩
新认识1
标签的实现.jpg
- (void)customWith:(LikeModel *)model{
    [self.iconImage sd_setImageWithURL:[NSURL URLWithString:model.image]];
    self.titleL.text = model.title;
    self.desL.text = model.Description;
    for (id view in self.tagsView.subviews) {
        [view removeFromSuperview];
    }
    NSInteger i = 0;
    CGFloat orginX = 0;
    CGFloat btnH = 25;
    CGSize btnSize = CGSizeMake(100, 25);
    for (TagsInfoModel * tagInfo in model.tagsInfo) {
        NSString * text = tagInfo.text;
        CGRect rect = [text boundingRectWithSize:btnSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12]} context:nil];
        UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(orginX + 15, 0, rect.size.width + 20, btnH);
        btn.tag = 1000 + i;
        btn.titleLabel.font = [UIFont systemFontOfSize:12];
        orginX += btn.frame.size.width + 15;
        i +=1;
        btn.layer.cornerRadius = btnH / 2;
        btn.layer.masksToBounds = true;
        btn.layer.borderColor = [[UIColor orangeColor] CGColor];
        btn.layer.borderWidth = 0.8;
        [btn setTitle:text forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.tagsView addSubview:btn];
        

    }

新认识2

根据button 上的标题字数 来进行 选中 和不选中状态下不不同表现

第一种方式添加
let name = (self.loveArr![i]["name"] as! String)

//            let range = name.startIndex..<name.endIndex
            let nameRange:NSRange = NSMakeRange(0, name.characters.count)
            let normalAttribute = NSMutableAttributedString.init(string:name)
            normalAttribute.addAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 15),NSForegroundColorAttributeName:UIColor.black], range:nameRange)
            let selectedAttribute =  NSMutableAttributedString.init(string:name)
            selectedAttribute.addAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 17),NSForegroundColorAttributeName:NavColor], range: nameRange)
button.setTitleColor(UIColor.black, for: UIControlState.highlighted)
            button.setAttributedTitle(normalAttribute, for: UIControlState.normal)
            button.setAttributedTitle(selectedAttribute, for: UIControlState.selected)
第二种方式添加(建议用)
 NSMutableAttributedString * selectedAttributed = [[NSMutableAttributedString alloc]initWithString:self.btnsTitles[i] attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:25],NSForegroundColorAttributeName:[UIColor orangeColor]}];
 [button setAttributedTitle:selectedAttributed forState:UIControlStateSelected]; // 选中状态下的 大小 和 颜色
上一篇 下一篇

猜你喜欢

热点阅读