ios – 创建UIButton(UIButtonTypeCustom),顶部带有图像,底部带有AutoLayout标签

前端之家收集整理的这篇文章主要介绍了ios – 创建UIButton(UIButtonTypeCustom),顶部带有图像,底部带有AutoLayout标签前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在它的底部显示带有文本(单/多行)的按钮.顶部的图像(必须看起来是圆形的);图像&单击时必须突出显示文本.像这样:

这是viewDidLoad中的代码

btArtAndPainting = [UIButton buttonWithType:UIButtonTypeCustom];
btArtAndPainting.backgroundColor = [[UIColor cyanColor] colorWithAlphaComponent:1.00f];

btArtAndPainting.translatesAutoresizingMaskIntoConstraints = NO;
self.vwContainer.translatesAutoresizingMaskIntoConstraints = NO;

[self.vwContainer addSubview:btArtAndPainting];

[btArtAndPainting setImage:[UIImage imageNamed:kIMGCategoryArtAndPaintingNormal] forState:UIControlStateNormal];
[btArtAndPainting setImage:[UIImage imageNamed:kIMGCategoryArtAndPaintingHighlighted] forState:UIControlStateHighlighted];

[btArtAndPainting setTitle:@"Art and Painting" forState:UIControlStateNormal];
[btArtAndPainting setTitle:@"Art and Painting" forState:UIControlStateHighlighted];

btArtAndPainting.tintColor = [UIColor redColor];
btArtAndPainting.titleLabel.font = [UIFont systemFontOfSize:10.00f];
btArtAndPainting.titleLabel.textColor = [UIColor whiteColor];
btArtAndPainting.titleLabel.textAlignment = NSTextAlignmentCenter;
btArtAndPainting.titleLabel.lineBreakMode = NSLineBreakByWordWrapping | NSLineBreakByTruncatingTail;
btArtAndPainting.titleLabel.numberOfLines = 0;
btArtAndPainting.imageEdgeInsets = UIEdgeInsetsMake(0.00f,8.00f,20.00f,8.00f);
btArtAndPainting.titleEdgeInsets = UIEdgeInsetsMake(32.00f,0.00f,0.00f);

NSArray *constraintsWidth = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[btArtAndPainting(60)]|"
                                                                     options:0
                                                                     metrics:nil
                                                                       views:viewDictionary];

NSArray *constraintsHeight = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[searchBar]-10-[btArtAndPainting(60)]"
                                                                    options:0
                                                                    metrics:nil
                                                                      views:viewDictionary];

[self.vwContainer addConstraints:constraintsHeight];
[self.vwContainer addConstraints:constraintsWidth];

[btArtAndPainting layoutIfNeeded];
[btArtAndPainting needsUpdateConstraints];

问题是文本根本不显示(在正常和突出显示的状态下).请参阅下面的链接图像.
如何使用UIEdgeInset为文本腾出空间?我也试过创建一个UIButton类,但效果大致相同.

解决方法

请使用以下代码设置插图,
CGFloat spacing = 1.0;
CGSize imageSize = btArtAndPainting.imageView.frame.size;
btArtAndPainting.titleEdgeInsets = UIEdgeInsetsMake(0.0,- imageSize.width,- (imageSize.height + spacing),0.0);
CGSize titleSize = btArtAndPainting.titleLabel.frame.size;
btArtAndPainting.imageEdgeInsets = UIEdgeInsetsMake(- (titleSize.height + spacing),0.0,- titleSize.width);

希望这可以帮助..

猜你在找的iOS相关文章