this article reprinted to http://my.oschina.net/sayonala/blog/198376after an afternoon of consulting data and attempts, the final solution to the picture and text vertical arrangement, if the text length changes will cause the picture position change problem.
After an afternoon of access to information and try to finally solve the picture and text vertically arranged in the case, if the text length changes will cause the picture position change problem, the first use of online more than the practice, as follows:
?
12345678910111213141516171819202122232425262728 |
@interface UIButton (UIButtonExt)
- (
void
)centerImageAndTitle:(
float
)space;
- (
void
)centerImageAndTitle;
@end
@implementation UIButton (UIButtonExt)
- (
void
)centerImageAndTitle:(
float
)spacing
{
// get the size of the elements here for readability
CGSize imageSize = self.imageView.frame.size;
CGSize titleSize = self.titleLabel.frame.size;
// get the height they will take up as a unit
CGFloat totalHeight = (imageSize.height + titleSize.height + spacing);
// raise the image and push it right to center it
self.imageEdgeInsets = UIEdgeInsetsMake(- (totalHeight - imageSize.height), 0.0, 0.0, - titleSize.width);
// lower the text and push it left to center it
self.titleEdgeInsets = UIEdgeInsetsMake(0.0, - imageSize.width, - (totalHeight - titleSize.height),0.0);
}
- (
void
)centerImageAndTitle
{
const
int
DEFAULT_SPACING = 6.0f;
[self centerImageAndTitle:DEFAULT_SPACING];
}
@end
|
After testing, if the text length of the button change, will cause the picture position changes, after several changes uiedgeinsets value also did not achieve the desired effect, the final adoption of integrated UIButton class, rewrite layoutsubviews function implementation, special results recorded, For follow-up review
?
123456789101112131415161718 |
-(
void
)layoutSubviews {
[super layoutSubviews];
// Center image
CGPoint center = self.imageView.center;
center.x = self.frame.size.width/2;
center.y = self.imageView.frame.size.height/2;
self.imageView.center = center;
//Center text
CGRect newFrame = [self titleLabel].frame;
newFrame.origin.x = 0;
newFrame.origin.y = self.imageView.frame.size.height + 5;
newFrame.size.width = self.frame.size.width;
self.titleLabel.frame = newFrame;
self.titleLabel.textAlignment = UITextAlignmentCenter;
}
|
By rewriting, reset the ImageView center and the Titlelabel frame to solve the above problem.
IOS UIButton Set Picture text vertical arrangement