選中按鈕改變文字大小和顏色

餘默發表於2018-07-06
  • 這是一個比較實用的小功能,可以根據專案的需求而改變按鈕的屬性,這裡我只是針對我的專案寫出來的一個簡單demo,需要想給在外部控制button的顏色和文字大小,可以給他封裝一個方法或者新增兩個屬性即可。程式碼奉上:
  • 這個功能的效果如下

選中按鈕改變文字大小和顏色

//  YMChangeButton.m
//
 
#import "YMChangeButton.h"
 
#define LabelFontRegular(t) [UIFont fontWithName:@"PingFangHK-Regular" size:(t)]
 
@implementation YMChangeButton
 
//xib
- (void)awakeFromNib
{
    [super awakeFromNib];
}
 
//純程式碼
- (instancetype)initWithFrame:(CGRect)frame
{
    if ([super initWithFrame:frame]) {
        
    }
    return self;
}
 
- (void)layoutSubviews
{
    [super layoutSubviews];
    
    NSRange range = [self.titleLabel.text rangeOfString:self.titleLabel.text];
    
    //設定普通狀態下的文字屬性
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:self.titleLabel.text];
    [attributedStr addAttribute:NSFontAttributeName value:LabelFontRegular(15) range:range];
    [attributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor purpleColor] range:range];
    [self setAttributedTitle:attributedStr forState:UIControlStateNormal];
    
    //設定選中狀態下的文字屬性
    NSMutableAttributedString *attributedStrS = [[NSMutableAttributedString alloc] initWithString:self.titleLabel.text];
    [attributedStrS addAttribute:NSFontAttributeName value:LabelFontRegular(20) range:range];
    [attributedStrS addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
    [self setAttributedTitle:attributedStrS forState:UIControlStateSelected];
    
}
 
@end
複製程式碼


  • 這個類的使用方法如下:

//  ViewController.m
//
 
#import "ViewController.h"
#import "UIView+MHExtension.h"
#import "YMChangeButton.h"
 
@interface ViewController ()
 
/** 當前選中的標題按鈕 */
@property (nonatomic, weak) YMChangeButton *selectedTitleButton;
 
@end
 
@implementation ViewController
 
- (void)viewDidLoad {
    [super viewDidLoad];
    
    CGFloat buttonW = 200;
    CGFloat buttonH = 60;
    for (int i = 0; i < 5; i++) {
        YMChangeButton *button = [[YMChangeButton alloc] init];
        button.mh_x = 100;
        button.mh_y = i * (buttonH + 50) + 100;
        button.mh_width = buttonW;
        button.mh_height = buttonH;
        
        button.backgroundColor = [UIColor greenColor];
        [button setTitle:@"測試" forState:UIControlStateNormal];
        
        button.tag = i;
        
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.view addSubview:button];
    }
    
    NSLog(@"%@",self.view.subviews);
    YMChangeButton *firstTileButton = self.view.subviews.lastObject;
    firstTileButton.selected = YES;
    self.selectedTitleButton = firstTileButton;
}
 
- (void)buttonClick:(YMChangeButton *)sender
{
    
    self.selectedTitleButton.selected = NO;
    sender.selected = YES;
    self.selectedTitleButton = sender;
    
    
    NSLog(@"111");
}

複製程式碼

雖然這個功能寫的不怎麼樣,但是對於新手來說也是不錯的demo,歡迎留言。

相關文章