zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

iOS调整按纽图片文字title位置的代码详解手机开发

ios手机代码开发 详解 图片 调整 位置
2023-06-13 09:20:12 时间

自定义一个button,要调整 button中的image(注意,不是backgroundImage) 和  title 文字的位置,只需要重写  Button类独对应的两个方法即可:

首先,我们来创建一个 SuperButton继承自 UIButton

 // 

 // SuperButton.h 

 // SuperButton #import UIKit/UIKit.h 

 @interface SuperButton : UIButton 

 @end 

实现文件


[self setTitle:@"项目介绍" forState:UIControlStateNormal]; [self.titleLabel setFont:[UIFont boldSystemFontOfSize:font]]; [self setBackgroundImage:[UIImage imageNamed:@"[email protected]"] forState:UIControlStateNormal]; [self setImage:[UIImage imageNamed:@"[email protected]"] forState:UIControlStateNormal]; boundingRect=[self.titleLabel.text boundingRectWithSize:CGSizeMake(320,font) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]} context:nil]; return self; }



 1.重写方法,改变 图片的位置 在 titleRect..方法后执行 

 - (CGRect)imageRectForContentRect:(CGRect)contentRect 

 CGFloat imageX=self.frame.size.width/2+boundingRect.size.width/2; 

 UIScreen *s=[UIScreen mainScreen]; 

 CGRect rect=s.bounds; 

 CGFloat imageY=contentRect.origin.y+14; 

 CGFloat width=24; 

 CGFloat height=24; 

 return CGRectMake(imageX, imageY, width, height); 

 2.改变title文字的位置,构造title的矩形即可 

 - (CGRect)titleRectForContentRect:(CGRect)contentRect 

 CGFloat imageX=(self.frame.size.width-boundingRect.size.width)/2; 

 CGFloat imageY=contentRect.origin.y+10; 

 CGFloat width=220; 

 CGFloat height=25; 

 return CGRectMake(imageX, imageY, width, height); 

 @end 



我们只要重写 上述的两个方法,就可以实现对 button按钮中的图片和文字的位置的调整 
注意: 

1.ios7和ios8系统上 上述两个方法 运行的次数会有差异,可以设置标志位,或者自定义一个 button(不要集成button)