IOS summaryimplement UIButton text-and-image mixing and display text and images at the same time

Source: Internet
Author: User

IOS summaryimplement UIButton text-and-image mixing and display text and images at the same time

Buttons are often used to display text and images at the same time. For example:


We need to define a UIButton subclass.


Implementation File


-(Id) initWithFrame :( CGRect) frame


Self = [super initWithFrame: frame];

If (self ){

// You can adjust it as needed

Self. titleLabel. textAlignment = NSTextAlignmentRight;

Self. titleLabel. font = [UIFont systemFontOfSize: 14.0];

Self. imageView. contentMode = UIViewContentModeLeft;


Return self;


// Override the UIButton method of the parent class


// More button-specific rect settings and return the rect of the text label

-(CGRect) titleRectForContentRect :( CGRect) contentRect


CGFloat titleW = contentRect. size. width-30;

CGFloat titleH = contentRect. size. height;

CGFloat titleX = 0;

CGFloat titleY = 0;


ContentRect = (CGRect) {titleX, titleY}, {titleW, titleH }};

Return contentRect;



// More button-specific rect settings and returned UIImageView rect

-(CGRect) imageRectForContentRect :( CGRect) contentRect


CGFloat imageW = 25;

CGFloat imageH = 25;

CGFloat imageX = contentRect. size. width-26;

CGFloat imageY = 2.5;


ContentRect = (CGRect) {imageX, imageY}, {imageW, imageH }};

Return contentRect;




// Use the UIButton subclass

YxpButton * selectAreaButton = [[yxpButton alloc] initWithFrame: CGRectMake (200, 5,100, 30)];

[SelectAreaButton setTitle: @ "" forState: UIControlStateNormal];

[SelectAreaButton setImage: [UIImage imageNamed: @ "location"] forState: UIControlStateNormal];

[SelectAreaButton setTitleColor: [UIColor whiteColor] forState: UIControlStateNormal];

[NavigationBgView addSubview: selectAreaButton];

In this way, we can achieve the text mixing of a button.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.