选中按钮改变文字大小和颜色
Posted 氵如止水
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了选中按钮改变文字大小和颜色相关的知识,希望对你有一定的参考价值。
这是一个比较实用的小功能,可以根据项目的需求而改变按钮的属性,这里我只是针对我的项目写出来的一个简单demo,需要想给在外部控制button的颜色和文字大小,可以给他封装一个方法或者添加两个属性即可。代码奉上:
这个功能的效果如下:
//
// YMChangeButton.h
//
#import <UIKit/UIKit.h>
@interface YMChangeButton : UIButton
@end
//
// 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,欢迎各位大神指教。
以上是关于选中按钮改变文字大小和颜色的主要内容,如果未能解决你的问题,请参考以下文章