UIButton with a caption below the image

I want to create a UIButton programmatically with a title below the image.

Button size: 170 * 120 Imge size: 50 * 50 Title size: depends on the text.

I know what I need to use, but I do not know how:

[_button setTitleEdgeInsets:UIEdgeInsetsMake(0.f, 0.f, 0.f, 0.f)]; [_button setImageEdgeInsets:UIEdgeInsetsMake(0.f, 0.f, 0.f, 0.f)]; 

I think I should calculate the size of the header and then use EdgeInsets.

Thanks.

+4
source share
2 answers

The ultimate and stable solution is to use the frame solution, not EdgeInset :

 @interface UIButton (UIButtonExt) (void)centerImageAndTitleEx; @end @implementation UIButton (UIButtonExt) (void)centerImageAndTitleEx { CGRect frame = self.imageView.frame; frame = CGRectMake(truncf((self.bounds.size.width - frame.size.width) / 2), 10.0f, frame.size.width, frame.size.height); self.imageView.frame = frame; frame = self.titleLabel.frame; frame = CGRectMake(truncf((self.bounds.size.width - frame.size.width) / 2), self.bounds.size.height - frame.size.height - 5.0, frame.size.width, frame.size.height); self.titleLabel.frame = frame; } @end 
+4
source

Hope this helps you.

 @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 
+19
source

Source: https://habr.com/ru/post/1438279/


All Articles