ios 如何将图像放在 UIButton 中文本的右侧?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7100976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 21:09:55  来源:igfitidea点击:

How do I put the image on the right side of the text in a UIButton?

iosuser-interfacelayoutuibutton

提问by jasongregori

I don't want to use a subview if I can avoid it. I want a UIButtonwith a background image, text, and an image in it. Right now, when I do that, the image is on the left side of the text. The background image, text, and image all have different highlight states.

如果可以避免,我不想使用子视图。我想要一个UIButton带有背景图像、文本和图像的图像。现在,当我这样做时,图像位于文本的左侧。背景图像、文本和图像都有不同的高亮状态。

采纳答案by Benjamin

Despite some of the suggested answers being very creative and extremely clever, the simplest solution is as follows:

尽管一些建议的答案非常有创意且非常聪明,但最简单的解决方案如下:

button.semanticContentAttribute = UIApplication.shared
    .userInterfaceLayoutDirection == .rightToLeft ? .forceLeftToRight : .forceRightToLeft

As simple as that. As a bonus, the image will be at the left side in right-to-left locales.

就如此容易。作为奖励,图像将在从右到左的语言环境中位于左侧。

EDIT: as the question has been asked a few times, this is iOS 9 +.

编辑:因为这个问题已经问过几次了,这是iOS 9 +

回答by Liau Jian Jie

Simplest solution:

最简单的解决方案:

iOS 10 & up, Swift:

iOS 10 及更高版本,Swift:

button.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
button.titleLabel?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
button.imageView?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)

Before iOS 10, Swift/Obj-C:

在 iOS 10 之前,Swift/Obj-C:

button.transform = CGAffineTransformMakeScale(-1.0, 1.0);
button.titleLabel.transform = CGAffineTransformMakeScale(-1.0, 1.0);
button.imageView.transform = CGAffineTransformMakeScale(-1.0, 1.0);

回答by Victor Rius

UPDATED FOR XCODE 9 (Via Interface Builder)

更新 XCODE 9(通过接口生成器)

There's an easier way from the Interface Builder.

Interface Builder 提供了一种更简单的方法。

Select the UIButton and select this option in the View Utilities > Semantic:

选择 UIButton 并在 View Utilities > Semantic 中选择此选项:

left-to-rightenter image description hereThat's it! Nice and simple!

左到右在此处输入图片说明就是这样!好看又简单!

OPTIONAL- 2nd step:

可选- 第 2 步:

If you want to adjust the spacing between the image and the title you can change the Image Insethere:

如果要调整图像和标题之间的间距,可以在此处更改图像插入

enter image description here

在此处输入图片说明

Hope that helps!

希望有帮助!

回答by Ben Baron

Subclassing UIButton is completely unnecessary. Instead you can simply set a high left inset value for the image insets, and a small right inset for the title. Something like this:

子类化 UIButton 是完全没有必要的。相反,您可以简单地为图像插入设置一个高的左插入值,并为标题设置一个小的右插入值。像这样的东西:

button.imageEdgeInsets = UIEdgeInsetsMake(0., button.frame.size.width - (image.size.width + 15.), 0., 0.);
button.titleEdgeInsets = UIEdgeInsetsMake(0., 0., 0., image.size.width);

回答by jasongregori

I'm giving Inspire48the credit for this one. Based on his suggestion and looking at that other question I came up with this. Subclass UIButton and override these methods.

这个功劳归功于Inspire48。根据他的建议并查看另一个问题,我想出了这个。子类化 UIButton 并覆盖这些方法。

@implementation UIButtonSubclass

- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
    CGRect frame = [super imageRectForContentRect:contentRect];
    frame.origin.x = CGRectGetMaxX(contentRect) - CGRectGetWidth(frame) -  self.imageEdgeInsets.right + self.imageEdgeInsets.left;
    return frame;
}

- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
    CGRect frame = [super titleRectForContentRect:contentRect];
    frame.origin.x = CGRectGetMinX(frame) - CGRectGetWidth([self imageRectForContentRect:contentRect]);
    return frame;
}

@end

回答by Piotr Tomasik

Just update the insets when the title is changed. You need to compensate for the inset with an equal and opposite inset on the other side.

更改标题时只需更新插图。您需要在另一侧使用相等且相反的插图来补偿插图。

[thebutton setTitle:title forState:UIControlStateNormal];
thebutton.titleEdgeInsets = UIEdgeInsetsMake(0, -thebutton.imageView.frame.size.width, 0, thebutton.imageView.frame.size.width);
thebutton.imageEdgeInsets = UIEdgeInsetsMake(0, thebutton.titleLabel.frame.size.width, 0, -thebutton.titleLabel.frame.size.width);

回答by barndog

All of these answers, as of January 2016, are unnecessary. In Interface Builder, set the View Semantic to Force Right-to-Left, or if you prefer programmatic way, semanticContentAttribute = .forceRightToLeftThat will cause the image to appear on the right of your text.

截至 2016 年 1 月,所有这些答案都是不必要的。在 Interface Builder 中,将 View Semantic 设置为Force Right-to-Left,或者如果您更喜欢编程方式,semanticContentAttribute = .forceRightToLeft这将导致图像出现在文本的右侧。

回答by Gennadiy Ryabkin

In interface builder you can configure options Edge Insets for UIButton, separately each of three parts: content, image, title

在界面构建器中,您可以为 UIButton 配置选项 Edge Insets,分别为三个部分:内容、图像、标题

enter image description hereenter image description here

在此处输入图片说明在此处输入图片说明

Xcode 8:

代码 8:

enter image description here

在此处输入图片说明

回答by Jean-Baptiste

Update: Swift 3

更新:斯威夫特 3

class ButtonIconRight: UIButton {
    override func imageRect(forContentRect contentRect:CGRect) -> CGRect {
        var imageFrame = super.imageRect(forContentRect: contentRect)
        imageFrame.origin.x = super.titleRect(forContentRect: contentRect).maxX - imageFrame.width
        return imageFrame
    }

    override func titleRect(forContentRect contentRect:CGRect) -> CGRect {
        var titleFrame = super.titleRect(forContentRect: contentRect)
        if (self.currentImage != nil) {
            titleFrame.origin.x = super.imageRect(forContentRect: contentRect).minX
        }
        return titleFrame
    }
}

Original answer for Swift 2:

Swift 2 的原始答案:

A solution that handles all horizontal alignments, with a Swift implementation example. Just translate to Objective-C if needed.

处理所有水平对齐的解决方案,带有 Swift 实现示例。如果需要,只需转换为 Objective-C。

class ButtonIconRight: UIButton {
    override func imageRectForContentRect(contentRect:CGRect) -> CGRect {
        var imageFrame = super.imageRectForContentRect(contentRect)
        imageFrame.origin.x = CGRectGetMaxX(super.titleRectForContentRect(contentRect)) - CGRectGetWidth(imageFrame)
        return imageFrame
    }

    override func titleRectForContentRect(contentRect:CGRect) -> CGRect {
        var titleFrame = super.titleRectForContentRect(contentRect)
        if (self.currentImage != nil) {
            titleFrame.origin.x = CGRectGetMinX(super.imageRectForContentRect(contentRect))
        }
        return titleFrame
    }
}

Also worth noting that it handles quite well image & title insets.

同样值得注意的是,它可以很好地处理图像和标题插入。

Inspired from jasongregori answer ;)

灵感来自 jasongregori 答案;)

回答by tt.Kilew

If this need to be done in UIBarButtonItem, additional wrapping in view should be used
This will work

如果这需要在UIBarButtonItem中完成,则应使用视图中的额外包装
这将起作用

let view = UIView()
let button = UIButton()
button.setTitle("Skip", for: .normal)
button.setImage(#imageLiteral(resourceName:"forward_button"), for: .normal)
button.semanticContentAttribute = .forceRightToLeft
button.sizeToFit()
view.addSubview(button)
view.frame = button.bounds
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: view)

This won't work

这行不通

let button = UIButton()
button.setTitle("Skip", for: .normal)
button.setImage(#imageLiteral(resourceName:"forward_button"), for: .normal)
button.semanticContentAttribute = .forceRightToLeft
button.sizeToFit()
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)