美文网首页
iOS 按钮 文字在左 图片在右实现代码

iOS 按钮 文字在左 图片在右实现代码

作者: 1b3bd36d9d21 | 来源:发表于2016-07-15 17:49 被阅读13394次

依然直接上代码,很简单 2行 就实现
第一种解决方案:

    UIButton *leftBtn = [[UIButton alloc] init];
    [leftBtn setTitle:@"北京" forState:UIControlStateNormal];
    [leftBtn setImage:[UIImage imageNamed:@"选择城市箭头"] forState:UIWindowLevelNormal];
    leftBtn.titleLabel.font = kFont(13);
    leftBtn.frame = CGRectMake(0, 0, 40, 44);
    leftBtn.showsTouchWhenHighlighted = YES;
    leftBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -5, 0, 0);
    // 重点位置开始
    leftBtn.imageEdgeInsets = UIEdgeInsetsMake(0, leftBtn.titleLabel.width + 2.5, 0, -leftBtn.titleLabel.width - 2.5);
    leftBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -leftBtn.currentImage.size.width, 0, leftBtn.currentImage.size.width);
    // 重点位置结束
    leftBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    UIBarButtonItem *leftItemBtn = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    
    self.navigationItem.leftBarButtonItem = leftItemBtn;

第二种解决方案:

    自定义一个按钮集成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 + 13;
//    self.imageView.center = center;
//    
//    //    self.imageView.height = 27.0;
//    //    self.imageView.width = 28.0;
//    
//    //Center text
//    CGRect newFrame = [self titleLabel].frame;
//    newFrame.origin.x = 0;
//    newFrame.origin.y = CGRectGetMaxY(self.imageView.frame) + 5;
//    newFrame.size.width = self.frame.size.width;
//    
//    self.titleLabel.frame = newFrame;
//    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    
    CGRect titleF = self.titleLabel.frame;
    CGRect imageF = self.imageView.frame;
    
    titleF.origin.x = 0;
    self.titleLabel.frame = titleF;
    
    imageF.origin.x = CGRectGetMaxX(titleF) + 10;
    self.imageView.frame = imageF;
}
  • 提示
    当设置后,文字依然跑偏,解决方案:首先排查是否设置了setImage图片或者是否调用了[self.button layoutIfNeeded];

相关文章

网友评论

      本文标题:iOS 按钮 文字在左 图片在右实现代码

      本文链接:https://www.haomeiwen.com/subject/dkiyjttx.html