UIButton Image Align问题

时间:2015-05-18 19:11:57

标签: ios iphone

我得到了CheckBox Image,这是UIButton上带文字的顶部。我有问题将文本与Letf和Image对齐。什么是UIButton的宽度,文本应该左对齐,图像应该对齐。我试过可能会回答。但我没有准确的文字。请帮帮我。

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic, strong) UIButton* checkBoxBtn;
@end

@implementation ViewController

- (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    CGFloat LableHeight = 40;
    self.checkBoxBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.checkBoxBtn.frame = CGRectMake(50, 150, 150, LableHeight);
    self.checkBoxBtn.center = self.view.center;
    self.checkBoxBtn.backgroundColor = [UIColor lightGrayColor];
    [self.checkBoxBtn setTitle:@"Alert Me" forState:UIControlStateNormal];
    [self.checkBoxBtn setImage:[self imageWithImage:[UIImage imageNamed:@"checkBoxUnChecked"] scaledToSize:CGSizeMake(LableHeight, LableHeight)] forState:UIControlStateNormal];
    [self.checkBoxBtn setImage:[self imageWithImage:[UIImage imageNamed:@"checkBoxChecked"] scaledToSize:CGSizeMake(LableHeight, LableHeight)] forState:UIControlStateSelected];
    self.checkBoxBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    self.checkBoxBtn.contentVerticalAlignment = UIControlContentHorizontalAlignmentCenter;
    [self.view addSubview:self.checkBoxBtn];

    [self.checkBoxBtn addTarget:self action:@selector(checkBoxBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)checkBoxBtnTapped:(UIButton*)sender
{

    BOOL isSelected = sender.selected;
    if (isSelected) {
        [sender setSelected:NO];
    }
    else {
        [sender setSelected:YES];
    }
}

@end

0 个答案:

没有答案