iPhone SDK: UIButton既支持图片又支持文本?

时间:2021-05-25 10:44:26

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. Anybody have ideas for it? Please let me know if you don't understand my question.

我有一个宽200,高270的按钮。我想让文本和图像在同一个按钮上。而不是文本的背景图像。相反,我想在同一个按钮上显示高度为120的文本和高度为150的图像。有人有想法吗?如果你不明白我的问题,请告诉我。

8 个解决方案

#1


110  

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.

在nib文件>中获取一个UIButton使它成为一个自定义按钮>将IBOutlet连接到nib文件中的自定义按钮。这是它。

#2


14  

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

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

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];

#3


5  

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

#4


5  

Use the concept of subviews. Take 3 controls, UIButton (200x270), UILabel (200x120) and UIImageView (200x150). Assign the image to the UIImageView and 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的(x,y)位置定位标签和imageview控件。

In the end, you should have something like:

最后,你应该有这样的东西:

For the following instances:

下面的实例:

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

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

#5


4  

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 contentVerticalAlignment and contentHorizontalAlignment properties of the UIButton (inherited from UIControl).

您可以使用UIButton(继承自UIControl)的contentVerticalAlignment和contentHorizontalAlignment属性。

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

您还可以使用titleEdgeInsets和imageEdgeInsets属性将标题和图像从基于对齐属性得到的位置上移动。

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.titleLabel inside of titleRectForContentRect:, make sure self.currentTitle is defined first. I was getting a bad access error, , possibly the method is called when first initializing the titleLabel.

如果您想要非常准确或自定义的放置,我建议重写UIButton的titleRectForContentRect:和imageRectForContentRect:方法。它们允许您为标题和图像定义框架,每当需要设置按钮时就会调用它们。一个警告,如果你想引用self。titleelabel在titleRectForContentRect里面:,确保self。currentTitle首先定义。我得到了一个错误的访问错误,可能是在第一次初始化titleLabel时调用这个方法。

#6


2  

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

如果以编程方式设置锚点,让它出现/附加到接口构建器中的按钮引用(如果使用故事板),请不要忘记设置锚点

#7


1  

If you want to have more control over the layout, create a subclass of UIControl and 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)。然后你可以定期使用自动布局,而不需要整理UIEdgeInsets。

#8


0  

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))
    

#1


110  

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.

在nib文件>中获取一个UIButton使它成为一个自定义按钮>将IBOutlet连接到nib文件中的自定义按钮。这是它。

#2


14  

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

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

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];

#3


5  

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

#4


5  

Use the concept of subviews. Take 3 controls, UIButton (200x270), UILabel (200x120) and UIImageView (200x150). Assign the image to the UIImageView and 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的(x,y)位置定位标签和imageview控件。

In the end, you should have something like:

最后,你应该有这样的东西:

For the following instances:

下面的实例:

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

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

#5


4  

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 contentVerticalAlignment and contentHorizontalAlignment properties of the UIButton (inherited from UIControl).

您可以使用UIButton(继承自UIControl)的contentVerticalAlignment和contentHorizontalAlignment属性。

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

您还可以使用titleEdgeInsets和imageEdgeInsets属性将标题和图像从基于对齐属性得到的位置上移动。

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.titleLabel inside of titleRectForContentRect:, make sure self.currentTitle is defined first. I was getting a bad access error, , possibly the method is called when first initializing the titleLabel.

如果您想要非常准确或自定义的放置,我建议重写UIButton的titleRectForContentRect:和imageRectForContentRect:方法。它们允许您为标题和图像定义框架,每当需要设置按钮时就会调用它们。一个警告,如果你想引用self。titleelabel在titleRectForContentRect里面:,确保self。currentTitle首先定义。我得到了一个错误的访问错误,可能是在第一次初始化titleLabel时调用这个方法。

#6


2  

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

如果以编程方式设置锚点,让它出现/附加到接口构建器中的按钮引用(如果使用故事板),请不要忘记设置锚点

#7


1  

If you want to have more control over the layout, create a subclass of UIControl and 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)。然后你可以定期使用自动布局,而不需要整理UIEdgeInsets。

#8


0  

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))