Uibutton的标题与左侧对齐,图像与右侧

时间:2017-06-16 08:44:42

标签: ios objective-c xcode

当我尝试使用以下选项创建UIButton时出现问题:标题左对齐,图像右对齐,

我想以编程方式进行,这是我到目前为止所尝试的,它有效,但不是我想要

UIButton *definition_title = [UIButton buttonWithType:UIButtonTypeRoundedRect];
              definition_title.frame = CGRectMake(0,0, accordion.frame.size.width, 70.0f);
              [definition_title setImage:[UIImage imageNamed:@"image_name.png"] forState:UIControlStateNormal];
              definition_title.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
              definition_title.imageView.contentMode = UIViewContentModeScaleAspectFit;
              [definition_title setTitle:@"Scan the Barcode" forState:UIControlStateNormal];
              definition_title.titleEdgeInsets = UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0f);
              definition_title.imageEdgeInsets = UIEdgeInsetsMake(0.0f, accordion.frame.size.width-50, 0.0f, 0.0f);
              definition_title.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

上面的代码像这样返回i Uibutton

    ________________
   |    text   image|

但我希望它像这样

    ________________
   |text       image|

1 个答案:

答案 0 :(得分:1)

方法1:

为按钮添加标题和图像,并调整标题和图像插入以使文本和图像显示在按钮的两侧

enter image description here

方法2:

创建UIButton的子类并覆盖func imageRect(forContentRect contentRect: CGRect) -> CGRectfunc titleRect(forContentRect contentRect: CGRect) -> CGRect,并为标题和图像提供CGRect。

示例:

import UIKit

class MyTestButton: UIButton {

    override func imageRect(forContentRect contentRect: CGRect) -> CGRect {
        return CGRect(x: self.frame.maxX - contentRect.height/*specify your button width here am using height */, y: 0, width: contentRect.height/*specify your button width here am using height */, height: contentRect.height)
    }

    override func titleRect(forContentRect contentRect: CGRect) -> CGRect {
        return CGRect(x:0, y:0, width: self.bounds.size.width - self.imageRect(forContentRect:contentRect).width,height: contentRect.height)
    }
}

<强> O / P:

enter image description here