我想以编程方式在 imageView 下创建一个带有标题的 UIButton。
按钮尺寸:170 * 120 图片尺寸:50 * 50 标题的大小:取决于文本。
我知道我必须使用,但我不知道如何:
[_button setTitleEdgeInsets:UIEdgeInsetsMake(0.f, 0.f, 0.f, 0.f)];
[_button setImageEdgeInsets:UIEdgeInsetsMake(0.f, 0.f, 0.f, 0.f)];
我想我应该计算标题的大小,然后使用 EdgeInsets。
谢谢。
最佳答案
希望对您有所帮助。
@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
关于ios - ImageView 下带有标题的 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12770751/