一个老生常谈的小设计
就是要让UIButton图片在上面,标题在下面。
比如:
账号登录.png实现这个设计的方法很多,这里说两种。
第一种,
创建UIImageView,UILabel,然后设置image和title
通过 addSubview 方法,把UIImageView和UILabel添加进UIButton。
例如:
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
[self.view addSubView:button];
UIImageView *btnImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 80, 50)];
btnImage.image = [UIImage imageNamed:@"accountIcon"];
[button addSubview:btnImage];
UILabel *btnLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 50, 80, 30)];
btnLabel.contentMode = UIViewContentModeCenter;
btnLabel.text = @"账号登录";
[button addSubview:btnLabel];
按照UIButton的高度和宽度设置UIImageView和UILabel的frame。
然后就是第二种。
- (void)setButtonImageAndTitleWithSpace:(CGFloat)spacing WithButton:(UIButton *)btn{
CGSize imageSize = btn.imageView.frame.size;
CGSize titleSize = btn.titleLabel.frame.size;
CGSize textSize = [btn.titleLabel.text sizeWithFont:btn.titleLabel.font];
CGSize frameSize = CGSizeMake(ceilf(textSize.width), ceilf(textSize.height));
if (titleSize.width + 0.5 < frameSize.width) {
titleSize.width = frameSize.width;
}
CGFloat totalHeight = (imageSize.height + titleSize.height + spacing);
btn.imageEdgeInsets = UIEdgeInsetsMake(- (totalHeight - imageSize.height), 0.0, 0.0, - titleSize.width);
btn.titleEdgeInsets = UIEdgeInsetsMake(0, - imageSize.width, - (totalHeight - titleSize.height), 0);
}
传入要设置的button,根据frame设置image和label的位置。
网友评论