博客> iOS UIButton 设置图标和文字垂直排列
iOS UIButton 设置图标和文字垂直排列
2017-08-16 15:35 评论:0 阅读:368 tianya2416
UIButton UIButton图片文字垂直排列

1、前言

一般情况下UIButton的图片和文字主要是左右排列,但是有时候我们需要的是图片和文字垂直排列。这时候有些人就会说可以使用UIButton的imageEdgeInsets和UIButton的titleEdgeInsets来调整他们的位置,使用imageEdgeInsets和titleEdgeInsets完全可实现图片和文字垂直排列。这边还有一种更好的方式,重新layoutSubviews实现图片和文字垂直排列。

2、重写UIButton的layoutSubviews来实现垂直排列

-(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;
}

通过重写,重新设置imageView的Center和titleLabel的Frame解决上述问题

3、imageEdgeInsets和titleEdgeInsets

UIImage * imageBg = [UIImage imageNamed:@"tanmu_default.png"];
float x = imageBg.size.width/2;
float y = imageBg.size.height/2;

UIImage * imageIcon = [UIImage imageNamed:@"tanmu_lock.png"];

UIButton * buttonCenterIcon = [UIButton buttonWithType:UIButtonTypeCustom];
[self.view addSubview:buttonCenterIcon];
[buttonCenterIcon setBackgroundImage:[imageBg stretchableImageWithLeftCapWidth:x topCapHeight:y] forState:UIControlStateNormal];

[buttonCenterIcon setImage:imageIcon forState:UIControlStateNormal];
[buttonCenterIcon setTitle:@"解锁" forState:UIControlStateNormal];
buttonCenterIcon.titleLabel.numberOfLines = 0;

CGSize imageSize = imageIcon.size;
CGSize titleSize = buttonCenterIcon.titleLabel.frame.size;

buttonCenterIcon.imageEdgeInsets = UIEdgeInsetsMake(- imageSize.width, 0.0, 0.0,- imageSize.height);

buttonCenterIcon.titleEdgeInsets = UIEdgeInsetsMake(0.0, - imageSize.width, - imageSize.height,0.0);

[buttonCenterIcon setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[buttonCenterIcon setFrame:CGRectMake(100, 100, 100,150)];

后面发现如果button的文字长度变化,会导致图片位置变化,经过多次修改UIEdgeInsets的值也没有达到期望效果,最终采用集成UIButton类,重写layoutSubviews函数实现。

收藏
0
sina weixin mail 回到顶部