ios UIButton 可以同时包含图像和文本吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4344847/
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 18:13:11  来源:igfitidea点击:

UIButton with both image and text possible?

iosiphonexcodeuibutton

提问by Viral Narshana

I have a button of size width 200 and height 270. I want to have text and image on the same button. Not as a background image on that text. Instead of this, I want to display the text with height 120 and image of height 150 on the same button. How to do it?

我有一个宽度为 200,高度为 270 的按钮。我想在同一个按钮上放置文本和图像。不作为该文本的背景图像。取而代之的是,我想在同一个按钮上显示高度为 120 的文本和高度为 150 的图像。怎么做?

回答by Aditya

You can use this code,it will serve your purpose

您可以使用此代码,它将满足您的目的

.h file code
IBOutlet UIButton *testBtn;

.m file code
[testBtn setImage: [UIImage imageNamed:@"Image name.png"] forState:UIControlStateNormal];
[testBtn setTitleEdgeInsets:UIEdgeInsetsMake(70.0, -150.0, 5.0, 5.0)];
[testBtn setTitle:@"Your text" forState:UIControlStateNormal];

Adjust the coordinates and size of your button as your requirement.This is a sample code to guide you.

根据您的要求调整按钮的坐标和大小。这是指导您的示例代码。

PS:Take a UIButton in the nib file>Make it a custom button>Connect the IBOutlet to your custom button in the nib file.Thats it.

PS:在nib文件中取一个UIButton>使其成为自定义按钮>将IBOutlet连接到nib文件中的自定义按钮。就是这样。

回答by Abhilash Reddy kallepu

The below code shows placing an image and text in a button using setImageEdgeInsets and setTitleEdgeInsets properties of UIButton class.

下面的代码显示了使用 UIButton 类的 setImageEdgeInsets 和 setTitleEdgeInsets 属性在按钮中放置图像和文本。

UIButton *butt=[UIButton buttonWithType:UIButtonTypeCustom ];
    [butt setFrame:CGRectMake(0, 0, 100, 100)];
    [butt setBackgroundImage:[UIImage imageNamed:@"sig.png"] forState:UIControlStateNormal];
    [butt setImageEdgeInsets:UIEdgeInsetsMake(0.0, 0.0, 50.0, 0.0)];
    [butt setTitleEdgeInsets:UIEdgeInsetsMake(75.0, 0.0, 0.0, 0.0)];
    [butt setTitle:@"hello" forState:UIControlStateNormal];
    [butt setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.view addSubview:butt];

回答by ohnit

Yes, you can display an image and a title in the same button, as long as they are both small enough to fit. The hard part comes, when you need to deal with placement.

是的,您可以在同一个按钮中显示图像和标题,只要它们都足够小以适合。当您需要处理放置时,困难的部分就来了。

You can play with the contentVerticalAlignmentand contentHorizontalAlignmentproperties of the UIButton(inherited from UIControl).

您可以使用(继承自)的contentVerticalAlignmentcontentHorizontalAlignment属性。UIButtonUIControl

You can also use the titleEdgeInsetsand imageEdgeInsetsproperties to shift the the title and image from the placement they get based on the alignment properties.

您还可以使用titleEdgeInsetsimageEdgeInsets属性根据对齐属性从它们获得的位置移动标题和图像。

If you want very accurate or custom placement, I suggest overriding the titleRectForContentRect:and imageRectForContentRect:methods of the UIButton. These allow you to define the frames for your title and image, and they are called whenever the button needs to be laid out. One warning, if you want to reference self.titleLabelinside of titleRectForContentRect:, make sure self.currentTitleis defined first. I was getting a bad access error, , possibly the method is called when first initializing the titleLabel.

如果你想非常准确的或定制的布局,我建议重写titleRectForContentRect:imageRectForContentRect:方法UIButton。这些允许您定义标题和图像的框架,并且在需要布置按钮时调用它们。一个警告,如果您想在self.titleLabel内部引用titleRectForContentRect:,请确保self.currentTitle首先定义。我遇到了错误的访问错误,可能是在第一次初始化 titleLabel 时调用了该方法。

回答by Vaishnavi Naidu

Use the concept of subviews. Take 3 controls, UIButton(200x270), UILabel(200x120) and UIImageView(200x150). Assign the image to the UIImageViewand set the text for the UILabel. Position your label and imageview controls based upon the (x,y) location of the UIButton.

使用子视图的概念。获取 3 个控件,UIButton(200x270)、UILabel(200x120) 和UIImageView(200x150)。将图像分配给UIImageView并为 设置文本UILabel。根据UIButton.

In the end, you should have something like:

最后,你应该有类似的东西:

For the following instances:

对于以下情况:

UIButton *button;
UILabel *label;
UIImageView *imageView;

[button addSubView:imageView];
[button addSubView:label];

回答by Amit Battan

[testBtn setBackgroudImage: [UIImage imageNamed:@"Image name.png"] forState:UIControlStateNormal];
[testBtn setTitle:@"Your text" forState:UIControlStateNormal];

回答by ColossalChris

In Swift 3

在斯威夫特 3

let button = UIButton()

//make sure the image (jpg, png) you are placing in the button
//is about the right size or it will push the label off the button

//add image
let image = UIImage(named:"my_button_image")
button.setImage(image, for: .normal)
button.imageView?.contentMode = .scaleAspectFit
button.imageEdgeInsets = UIEdgeInsets(top:0, left:-30, bottom:0, right:0) //adjust these to have fit right

//add title
button.setTitle("Fan", for: .normal)
button.titleEdgeInsets = UIEdgeInsets(top:0, left:10, bottom:0, right:0) //adjust insets to have fit how you want

//add button to your view - like in viewDidLoad or your own custom view setup
addSubview(button)

Don't forget to set anchors if doing so programmatically for it to appear/attach it to your button reference in Interface Builder if using a storyboard

如果以编程方式设置锚点,请不要忘记设置锚点,以便在使用故事板时将其显示/附加到界面生成器中的按钮引用

回答by orkoden

If you want to have more control over the layout, create a subclass of UIControland arrange the views you want (UILabel, UIImageView) in a xib file. Then you can use Autolayout regularly without having to sort out UIEdgeInsets.

如果你想对布局有更多的控制,创建一个子类,UIControl并在 xib 文件中排列你想要的视图 ( UILabel, UIImageView)。然后就可以定期使用Autolayout了,不用整理UIEdgeInsets

回答by Femi Loki

Using button subviews worked for me in Swift 4.

在 Swift 4 中使用按钮子视图对我有用。

  • Create your button
  • Set an image for button
  • Create a label for the text
  • Add the label as a subview of your button
  • Constrain the label within the button

           let imageAndTextButton : UIButton = {
                let button = UIButton(frame: .zero)
                button.tintColor = .clear
                button.setImage(#imageLiteral(resourceName: "buttonImage"), for: .normal)
                button.imageView?.contentMode = .scaleToFill
                button.translatesAutoresizingMaskIntoConstraints = false
                return button
            }()
            let textForButtonLabel = UILabel(frame: .zero)
            textForButtonLabel.translatesAutoresizingMaskIntoConstraints = false
            textForButtonLabel.attributedText = NSAttributedString(string: "Text For Button", attributes: buttonTextAttributes)
            textForButtonLabel.textAlignment = .center
            textForButtonLabel.backgroundColor = .clear
            imageAndTextButton.addSubview(textForButtonLabel)
            imageAndTextButton.addConstraint(NSLayoutConstraint(item: textForButtonLabel, attribute: .centerX, relatedBy: .equal, toItem: imageAndTextButton, attribute: .centerX, multiplier: 1.0, constant: 0))
            imageAndTextButton.addConstraint(NSLayoutConstraint(item: textForButtonLabel, attribute: .centerY, relatedBy: .equal, toItem: imageAndTextButton, attribute: .centerY, multiplier: 1.0, constant: 0))
    
  • 创建您的按钮
  • 为按钮设置图像
  • 为文本创建标签
  • 将标签添加为按钮的子视图
  • 约束按钮内的标签

           let imageAndTextButton : UIButton = {
                let button = UIButton(frame: .zero)
                button.tintColor = .clear
                button.setImage(#imageLiteral(resourceName: "buttonImage"), for: .normal)
                button.imageView?.contentMode = .scaleToFill
                button.translatesAutoresizingMaskIntoConstraints = false
                return button
            }()
            let textForButtonLabel = UILabel(frame: .zero)
            textForButtonLabel.translatesAutoresizingMaskIntoConstraints = false
            textForButtonLabel.attributedText = NSAttributedString(string: "Text For Button", attributes: buttonTextAttributes)
            textForButtonLabel.textAlignment = .center
            textForButtonLabel.backgroundColor = .clear
            imageAndTextButton.addSubview(textForButtonLabel)
            imageAndTextButton.addConstraint(NSLayoutConstraint(item: textForButtonLabel, attribute: .centerX, relatedBy: .equal, toItem: imageAndTextButton, attribute: .centerX, multiplier: 1.0, constant: 0))
            imageAndTextButton.addConstraint(NSLayoutConstraint(item: textForButtonLabel, attribute: .centerY, relatedBy: .equal, toItem: imageAndTextButton, attribute: .centerY, multiplier: 1.0, constant: 0))
    

回答by Jaywant Khedkar

Try this it's work for me ,

试试这个对我有用,

We have to set value of UIEdgeInsetsbase on our button size and requirement .

我们必须根据我们的按钮大小和要求设置UIEdgeInsets 的值。

[self.testButton setTitle: @"myTitle" forState: UIControlStateNormal];
UIImage *iconImage = [UIImage imageWithIcon:@"fa-dot-circle-o" backgroundColor:[UIColor clearColor] iconColor:[UIColor whiteColor] fontSize:10.0f];

//UIEdgeInsets insets = {top, left, bottom, right};

[self.testButton setImageEdgeInsets:UIEdgeInsetsMake(3.0, 0.0, 3.0, 2.0)];
[self.testButton setTitleEdgeInsets:UIEdgeInsetsMake(3.0, 1.0, 3.0, 0.0)];
[self.testButton setImage:iconImage forState:UIControlStateNormal];
[self.testButton addTarget:self action:@selector(testButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.testButton];

Hope This will help for some one .

希望这对某些人有所帮助。