代码自定义双色title的按钮

所图所示,通过代码自定义这样的按钮。

.h文件

//
//  CustomButtom.h
//  testPlus
//
//  Created by 鹰眼 on 14/10/20.
//  Copyright (c) 2014年 QCloud. All rights reserved.
//

#import <UIKit/UIKit.h>
#define KDefaultColor [UIColor colorWithRed:66/255.0 green:189/255.0 blue:146/255.0 alpha:1.0]
@interface CustomButtom : UIButton

-(void)setNumber:(NSString *)number andTitle:(NSString *)title;
@end

.m文件

 

//
//  CustomButtom.m
//  testPlus
//
//  Created by 鹰眼 on 14/10/20.
//  Copyright (c) 2014年 QCloud. All rights reserved.
//

#import "CustomButtom.h"

@implementation CustomButtom

-(instancetype)initWithFrame:(CGRect)frame
{
    self=[super initWithFrame:frame];
    if (self) {
        self.backgroundColor=[UIColor groupTableViewBackgroundColor];
        self.titleLabel.numberOfLines=0;
        self.titleLabel.textAlignment=NSTextAlignmentCenter;
        self.titleLabel.font=[UIFont systemFontOfSize:16.0];
        self.backgroundColor=[UIColor colorWithRed:53/255.0 green:65/255.0 blue:72/255.0 alpha:1.0];
    }
    return self;
    
}
-(void)setNumber:(NSString *)number andTitle:(NSString *)title
{
    [self setAttributedTitle:[self content:[NSString stringWithFormat:@"%@\n%@",number,title] colorString:number] forState:UIControlStateNormal];
}

-(NSAttributedString *)content:(NSString *)content colorString:(NSString *)search
{
    
    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:content];
    [attString addAttribute:(NSString*)NSForegroundColorAttributeName value:[UIColor whiteColor] range:[content rangeOfString:content]];
    [attString addAttribute:(NSString*)NSForegroundColorAttributeName value:KDefaultColor range:[content rangeOfString:search]];
    return attString;
}
@end

 通过这样就可以自定义拥有两个颜色的按钮了,完全可以不用图片实现。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值