ios - 是否可以让 UIButton 由文本组成,但最后有图像?

标签 ios objective-c uiview uibutton uilabel

例如,这样的按钮是否可以实现?

enter image description here

我见过像 this 这样的问题他们之前讨论过如何放置它,这确实很容易,但我不完全确定当文本可以是任何东西时如何将它附加到按钮上文本的末尾。从概念上讲,这就像有文本,然后 UIButton 在它的右边说 10pt。

执行此操作的最佳方法是否只是一个带有 UILabelUIImageViewUIView,并附有点击手势识别器?

最佳答案

快速示例:

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

    UIImage *img = [UIImage imageNamed:@"Arrow.png"];
    [button setTitle:@"A Button" forState:UIControlStateNormal];
    [button setImage:img forState:UIControlStateNormal];
    [button sizeToFit];

    CGRect imageRect = [button imageRectForContentRect:button.bounds];
    CGRect titleRect = [button titleRectForContentRect:button.bounds];

    UIEdgeInsets imageInset = UIEdgeInsetsZero;
    UIEdgeInsets titleInset = UIEdgeInsetsZero;

    titleInset.left = -2 * imageRect.size.width;
    imageInset.left = titleRect.size.width;

    button.titleEdgeInsets = titleInset;
    button.imageEdgeInsets = imageInset;
    [self.view addSubview:button];

    CGFloat prevHeight = button.frame.size.height;
    UIButton *anotherButton = [UIButton buttonWithType:UIButtonTypeCustom];

    [anotherButton setTitle:@"Another Button" forState:UIControlStateNormal];
    [anotherButton setImage:img forState:UIControlStateNormal];
    [anotherButton sizeToFit];

    imageRect = [anotherButton imageRectForContentRect:anotherButton.bounds];
    titleRect = [anotherButton titleRectForContentRect:anotherButton.bounds];

    imageInset = UIEdgeInsetsZero;
    titleInset = UIEdgeInsetsZero;

    titleInset.left = -2 * imageRect.size.width;
    imageInset.left = titleRect.size.width;

    anotherButton.titleEdgeInsets = titleInset;
    anotherButton.imageEdgeInsets = imageInset;

    CGRect frame = anotherButton.frame;
    frame.origin.y += prevHeight + 4;

    [anotherButton setFrame:frame];

    [self.view addSubview:anotherButton];
}

Result for 2 buttons create like this

如果你想在标题和图像之间添加空间,你只需要调整按钮大小和内嵌。

关于ios - 是否可以让 UIButton 由文本组成,但最后有图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20314337/

相关文章:

objective-c - 如何覆盖 Storyboard中定义的 UIBarButtonItem 触发的 segue

ios - Swift 3 - UIView 并不总是显示其内容

ios - 无法获取要加载的 iOS 应用程序接口(interface)来测试我的应用程序

iphone - 核心数据保存成功,但数据库中没有数据

ios - 自定义 MKAnnotation 点击​​范围

ios - 找到所有单例的 cocoa 类?

ios - 无法获取 UIView 的 subview

actionscript-3 - iOS下AS3保存本地文件

objective-c - NSURLConnection 泄漏问题

ios - 如何使用设置了背景图案的 UIView 并使用动画将其垂直缩小