UIButton titleEdgeInsets

时间:2013-08-28 09:57:43

标签: ios uibutton

titleEdgeInsets用于对齐按钮上的标题和图片。我在左边做了图像,在右边做了标题。但是当我点击按钮时,标题向左移动。谢谢

UIImage *image = [UIImage imageNamed:imageName];
    [self setImage:image forState:UIControlStateNormal];

CGSize imageSize = self.imageView.frame.size;
CGSize titleSize = self.titleLabel.frame.size;

self.imageEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
self.titleEdgeInsets = UIEdgeInsetsMake(0, ((self.frame.size.width-titleSize.width)/2)-imageSize.width, 0, 0);
self.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

status is normal

status is clicked

1 个答案:

答案 0 :(得分:16)

这是另一种直接设置标题和图像的方法----> :) 试试这种方式,

UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
aButton.frame = CGRectMake(0, 0, self.view.bounds.size.width, 40);
[aButton setImage:[UIImage imageNamed:@"imageName"] forState:UIControlStateNormal];
[aButton setTitle:@"Rate us on app store" forState:UIControlStateNormal];
[aButton setTitleEdgeInsets:UIEdgeInsetsMake(2, 50, 2, 20)];//set ur title insects also
[aButton setImageEdgeInsets:UIEdgeInsetsMake(2, -200, 2, 2)];//make negative edge for left side
[aButton setBackgroundColor:[UIColor greenColor]];
[self.view addSubview:aButton];