您的位置:首页 > 产品设计 > UI/UE

iOS -- UIButton上的文字、图片位置的调整

2016-07-04 09:45 411 查看
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">我们都知道UIButton上有titleLable和imageView,但是有时候我们不想用它默认的位置的,想要改变他的文字和图片的位置,那么如何来达到效果呢?</span>
简单思路就是:新建一个类继承于UIButton,重写两个函数,

       -(CGRect) imageRectForContentRect:(CGRect)contentRect ; 设置图片的位置

       -(CGRect) titleRectForContentRect:(CGRect)contentRect;      设置文字的位置

这样就可以随意设置button上的文字、图片的位置和大小了。

//自定义button的.m文件 

//重写父类方法设置按钮图片和文字的位置
-(CGRect)imageRectForContentRect:(CGRect)contentRect{

return CGRectMake(self.bounds.size.width*7/8, 10, self.bounds.size.width/8 , self.bounds.size.height/2);
}
-(CGRect)titleRectForContentRect:(CGRect)contentRect{
return CGRectMake(10, 0, self.bounds.size.width/2, self.bounds.size.height);
}


viewcontroller.m内容 :

- (void)viewDidLoad {
[super viewDidLoad];

MeButton *nameBtn = [[MeButton alloc]init];
[self addAButtonWithButton:nameBtn Bytitle:@"张三" Imagename:@"我的"];

nameBtn.sd_layout.centerXEqualToView(self.view).topSpaceToView(self.view,30).heightIs(35).widthRatioToView(self.view,0.9);

MeButton *button = [[MeButton alloc]init];
[self addAButtonWithButton:button Bytitle:@"修改密码" Imagename:@"向右"];
button.sd_layout.centerXEqualToView(self.view).topSpaceToView(nameBtn,10).heightIs(35).widthRatioToView(self.view,0.9);

}

#pragma mark -- 添加button相关方法
-(void)addAButtonWithButton:(UIButton *)button Bytitle:(NSString *)title Imagename:(NSString *)imageName{
[self.view addSubview:button];
[button.layer setMasksToBounds:YES];//设置按钮的圆角半径不会被遮挡

[button.layer setCornerRadius:10];

[button.layer setBorderWidth:1];//设置边界的宽度

//设置按钮的边界颜色

CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();

CGColorRef color = CGColorCreate(colorSpaceRef, (CGFloat[]){0,0,0,1});

[button.layer setBorderColor:color];

[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button setTitle:title forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: