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.