imageInset、titleInset

2016-12-01  本文已影响91人  乐视薯片

对于UIbutton的两个属性imageInset、titleInset一直没有太明白,最近研究了一下,对于不对的地方,欢迎指正啊。

首先要理解,这里的(top、left、bottom、right)并不是直接代表距离button的边界距离,而是现在的一个边界距离相对以前的偏移量,系统默认条件下,图片在左,文字在右。

接着就需要计算出原始image的宽高,title的原始位置,以及现在的位置,下面是简单实现的代码:

-(void)test1//图片在左,文字在右

{

self.button1.contentHorizontalAlignment=UIControlContentHorizontalAlignmentRight;

//self.button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

//以上这两个设置都是可以的

CGFloattitleWidth =60;

CGFloatshowImageWidth =30;

CGFloatoriginalImageWidth =self.button1.frame.size.width>ImageWidth?ImageWidth:self.button1.frame.size.width;

CGFloatleftInset = (self.button1.frame.size.width-titleWidth-showImageWidth)/2;

CGFloatrightInset = leftInset;

CGFloattitleOrigionX = originalImageWidth;

[self.button1setImageEdgeInsets:UIEdgeInsetsMake(0, leftInset,0, rightInset+titleWidth)];

[self.button1setTitleEdgeInsets:UIEdgeInsetsMake(0, leftInset+showImageWidth-titleOrigionX,0, rightInset)];

}

实现效果:

-(void)test2//文字在左,图片在右

{

//self.button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;

self.button1.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;

//以上这两种设置都可以

CGFloattitleWidth =60;

CGFloatshowImageWidth =30;

CGFloatoriginalImageWidth =self.button1.frame.size.width>ImageWidth?ImageWidth:self.button1.frame.size.width;

CGFloatleftInset = (self.button1.frame.size.width-titleWidth-showImageWidth)/2;

CGFloatrightInset = leftInset;

CGFloattitleOrigionX = originalImageWidth;

[self.button1setImageEdgeInsets:UIEdgeInsetsMake(0, leftInset+titleWidth,0, rightInset)];

[self.button1setTitleEdgeInsets:UIEdgeInsetsMake(0, leftInset-titleOrigionX,0, rightInset+showImageWidth)];

}

实现效果:

-(void)test3//图片在上,文字在下

{

//self.button2.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;

self.button2.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;

//以上这两个设置都是可以的

CGFloattitleWidth =60;

CGFloattitleHight =20;

CGFloatshowImageWidth =30;

CGFloatshowImageHight = showImageWidth;

CGFloatoriginalImageWidth =self.button2.frame.size.width>ImageWidth?ImageWidth:self.button2.frame.size.width;

CGFloattitleOrigionX = originalImageWidth;

CGFloatimageLeftInset = (self.button2.frame.size.width-showImageWidth)/2;

CGFloatimageRightInset = imageLeftInset;

CGFloattitleLeftInset = (self.button2.frame.size.width-titleWidth)/2;

CGFloattitleRightInset = titleLeftInset;

CGFloattopInset = (self.button2.frame.size.height-showImageHight-titleHight)/2;

CGFloatbottomInset = topInset;

[self.button2setImageEdgeInsets:UIEdgeInsetsMake(topInset,imageLeftInset, titleHight+bottomInset,imageRightInset)];

[self.button2setTitleEdgeInsets:UIEdgeInsetsMake(topInset+showImageHight, titleLeftInset-titleOrigionX, bottomInset, titleRightInset)];

}

实现效果:

上一篇下一篇

猜你喜欢

热点阅读