要实现的效果:
Paste_Image.png图片在文字之上显示,图片和文字都居中显示,可控制图片和文字之间的间距。
计算:
Paste_Image.png正常图片不设置按钮的 image和title的edgeinset的话正常布局是这样子的,左边上图片右边紧贴文字,s1和s2间距是一样的,如果文字太长的话会省略号显示,但是还是有s1和s2的间隙,如果按钮的宽度设置小于图片本身的宽度,文字就基本看不到了,图片宽度占满按钮的宽度,图片会被压缩适应显示。
Paste_Image.png算偏移【中心点偏移】
图片的位置偏移:
offx = (x1 + x2)0.5 - x10.5;
offy = (y1 + y2)0.5 - y10.5;
标题的位置偏移:
offx = (x1 + x2)0.5 - x20.5;
offy = (y1 + y2)0.5 - y20.5;
- (void)verticalHeightOffset:(CGFloat)heightOffset ver_space:(CGFloat)v_space
{
// self.backgroundColor = [UIColor redColor];
// self.imageView.backgroundColor = [UIColor blueColor];
// self.titleLabel.backgroundColor = [UIColor greenColor];
CGSize imageSize = self.imageView.frame.size;
CGSize titleSize1 = [[self currentTitle] boundingRectWithSize:CGSizeMake(FLT_MAX, FLT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.titleLabel.font} context:NULL].size;
CGSize titleSize2 = self.titleLabel.frame.size;
CGSize titleSize = CGSizeMake(ceil(MAX(titleSize1.width, titleSize2.width)), ceil(MAX(titleSize1.height, titleSize2.height)));
CGSize btnSize = self.frame.size;
float title_width = titleSize.width;
float title_width_stretch = 0;
if((imageSize.width + titleSize.width) > btnSize.width)
{
title_width = titleSize2.width;
title_width_stretch = (titleSize.width - titleSize2.width)*0.5;
}
float imgOffset_x = (imageSize.width + title_width)*0.5 - imageSize.width*0.5;
float height_content = imageSize.height + titleSize.height + v_space;
float imgOffset_y = height_content*0.5 - imageSize.height*0.5 + v_space*0.5 + heightOffset;
self.imageEdgeInsets = UIEdgeInsetsMake(-imgOffset_y , imgOffset_x, imgOffset_y, -imgOffset_x);
float titleOffset_x = (imageSize.width + title_width)*0.5 - title_width*0.5;
float titleOffset_y = height_content*0.5 - titleSize.height*0.5 - v_space *0.5 - heightOffset;
self.titleEdgeInsets = UIEdgeInsetsMake(titleOffset_y, -titleOffset_x-title_width_stretch, -titleOffset_y, titleOffset_x-title_width_stretch);
}
如果有其他方法 欢迎留言。
网友评论