现在好多APP特别是购物的有筛选排序, 像升序降序那种,最近项目做了个类似的分享给大家。
1.准备两个图片
2.定义UIButton子类
#import <UIKit/UIKit.h> typedef void(^DropBtnClickBlock)(BOOL isSeelect); @interface DropBtn : UIButton @property (nonatomic,strong) NSString *title; @property (nonatomic,strong) UIImageView *upOrDownImg; @property (nonatomic,copy) DropBtnClickBlock btnClickBlock; @end
#import "DropBtn.h" #define RGB(r,g,b) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1.0] @implementation DropBtn - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { _title=[[NSString alloc]init]; _upOrDownImg=[[UIImageView alloc]init]; _upOrDownImg.image=[UIImage imageNamed:@"yzp_data_dropdown.png"]; _upOrDownImg.frame=CGRectMake(self.frame.size.width-20-8, (frame.size.height-5)/2, 8, 5); [self addSubview:_upOrDownImg]; [self addTarget:self action:@selector(btnClickHandle:) forControlEvents:UIControlEventTouchUpInside]; } return self; } -(void)drawRect:(CGRect)rect { [super drawRect:rect]; //计算出字符串的frame NSDictionary *attributes[email protected]{NSFontAttributeName: [UIFont systemFontOfSize:20.f],NSForegroundColorAttributeName:RGB(26, 26, 26)}; CGRect frame=[_title boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil]; [_title drawAtPoint:CGPointMake((self.bounds.size.width-8-frame.size.width-20)/2, (self.bounds.size.height-frame.size.height)/2) withAttributes:attributes]; } -(void)btnClickHandle:(id)sender { UIButton *btn=(UIButton *)sender; btn.selected=!btn.selected; _btnClickBlock(btn.selected); } -(void)setSelected:(BOOL)selected { [super setSelected:selected]; if (!selected) { _upOrDownImg.image=[UIImage imageNamed:@"yzp_data_dropdown.png"]; } else { _upOrDownImg.image=[UIImage imageNamed:@"yzp_data_dropback.png"]; } } @end
3.调用
DropBtn *dropBtn=[[DropBtn alloc]initWithFrame:CGRectMake(0, 44, self.view.bounds.size.width/2, 60)]; dropBtn.title=@"价格"; dropBtn.backgroundColor=[UIColor yellowColor]; dropBtn.btnClickBlock=^(BOOL isSelected) { }; [self.view addSubview:dropBtn];
4.效果
时间: 2024-12-28 20:13:24