本文首发地址html
最近的项目中碰见的自定义的UIButton的状况出现不少种。有的时候以为要是放几个控件一拼接也能够达到效果。彷佛有点太low!!!因而乎就自定义本身的button了。ios
把title和image位置横向显示api
把till和image竖向显示微信
还有一些其余的状况就看本身心情了。(主要看项目需求了) 看自定义的button如何调用 1:效果图1的代码调用ide
// 中间按钮
TitleButton *titleButton = [TitleButton titleButton];
[titleButton setImage:[UIImage imageNamed:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
[titleButton setTitle:@"北京有限公司" forState:UIControlStateNormal];
titleButton.frame = CGRectMake(0, 0, 180, 40);
[titleButton addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.titleView = titleButton;
复制代码
2:效果图2的代码调用学习
SelleButton * btn = [SelleButton selleButton];
btn.frame = CGRectMake(100, 100, 80, 100);
[btn setTitle:@"张三" forState:UIControlStateNormal];
//[btn setBackgroundImage:[UIImage imageNamed:@"2bj"] forState:UIControlStateHighlighted];
[self.view addSubview:btn];
复制代码
看代码如何实现: 1:vc的.h文件以下spa
#import <UIKit/UIKit.h>
@interface MarkButton : UIButton
+ (instancetype)markButton;
@end
复制代码
2:vc的.m文件以下3d
#define MarkButtonTitleW 40
#import "MarkButton.h"
@implementation MarkButton
+ (instancetype)markButton
{
return [[self alloc] init];
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// 高亮的时候不要自动调整图标
self.adjustsImageWhenHighlighted = NO;
self.titleLabel.font = [UIFont boldSystemFontOfSize:15];
//self.titleLabel.textColor = [UIColor whiteColor];
self.imageView.contentMode = UIViewContentModeCenter;
self.titleLabel.textAlignment = NSTextAlignmentCenter;
// 背景
[self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
}
return self;
}
- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
CGFloat imageY = 0;
CGFloat imageX = 0;
CGFloat imageW = contentRect.size.width - MarkButtonTitleW;
CGFloat imageH = contentRect.size.height;
return CGRectMake(imageX, imageY, imageW, imageH);
}
- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
CGFloat titleY = 0;
CGFloat titleW = MarkButtonTitleW;
CGFloat titleX = contentRect.size.width - titleW;
CGFloat titleH = contentRect.size.height;
return CGRectMake(titleX, titleY, titleW, titleH);
}
@end
复制代码
3:详细介绍以下 查阅api系统官方给我咱们这几个方法code
- (CGRect)backgroundRectForBounds:(CGRect)bounds;
- (CGRect)contentRectForBounds:(CGRect)bounds;
- (CGRect)titleRectForContentRect:(CGRect)contentRect;
- (CGRect)imageRectForContentRect:(CGRect)contentRect;
复制代码
3.1重写Button的Titleorm
- (CGRect)titleRectForContentRect:(CGRect)contentRect;
复制代码
这里的contentRect就是你当前在使用自定义Button的title 的width和height。咱们重写这个方法,能够让button的title的位置变换位置和改变大小。 3.2 重写Button的Image
- (CGRect)imageRectForContentRect:(CGRect)contentRect;
复制代码
这里的contentRect就是你当前在使用自定义Button的image的width和height。咱们重写这个方法,能够让button的image的位置变换和改变大小。
3.3 剩下的两个方法就看各位了。 (提升装逼能力!!!)
若有问题可添加个人QQ:1290925041 还可添加QQ群:234812704(洲洲哥) 欢迎各位一块学习,提升逼格! 也能够添加洲洲哥的微信公众号 添加微信公众号最快最好的收听