Uibutton with title aligned to left and image alig

2019-09-19 17:49发布

问题:

I am having an issue while i try to create a UIButton with the following options: title aligned to left and image aligned on right,

I want to do it programatically, here is what i tryed so far, it works but not like i want to

UIButton *definition_title = [UIButton buttonWithType:UIButtonTypeRoundedRect];
              definition_title.frame = CGRectMake(0,0, accordion.frame.size.width, 70.0f);
              [definition_title setImage:[UIImage imageNamed:@"image_name.png"] forState:UIControlStateNormal];
              definition_title.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
              definition_title.imageView.contentMode = UIViewContentModeScaleAspectFit;
              [definition_title setTitle:@"Scan the Barcode" forState:UIControlStateNormal];
              definition_title.titleEdgeInsets = UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0f);
              definition_title.imageEdgeInsets = UIEdgeInsetsMake(0.0f, accordion.frame.size.width-50, 0.0f, 0.0f);
              definition_title.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

the code above returns i Uibutton like this

    ________________
   |    text   image|

but i want it like this

    ________________
   |text       image|

回答1:

Approach 1:

Add a title and a image to button and adjust the title and image insets to make the text and image appear on the sides of button

Approach 2:

Create a subclass of UIButton and override func imageRect(forContentRect contentRect: CGRect) -> CGRect and func titleRect(forContentRect contentRect: CGRect) -> CGRect and provide the CGRect for title and image.

Example :

import UIKit

class MyTestButton: UIButton {

    override func imageRect(forContentRect contentRect: CGRect) -> CGRect {
        return CGRect(x: self.frame.maxX - contentRect.height/*specify your button width here am using height */, y: 0, width: contentRect.height/*specify your button width here am using height */, height: contentRect.height)
    }

    override func titleRect(forContentRect contentRect: CGRect) -> CGRect {
        return CGRect(x:0, y:0, width: self.bounds.size.width - self.imageRect(forContentRect:contentRect).width,height: contentRect.height)
    }
}

O/P: