我有一个应用程序,其中UIButton
使用title
和UIImage
。他们的alignment
似乎是第一个标题,之后是UIImage
。
我试过这个:
[dropdownbutton setImage: [UIImage imageNamed:@"down_sml_arrow.png"]
forState:UIControlStateNormal];
CGFloat spacing = 10; // the amount of spacing to appear between image and title
dropdownbutton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, spacing);
dropdownbutton.titleEdgeInsets = UIEdgeInsetsMake(0, spacing, 0, 0);
[dropdownbutton setTitle:@"Your text" forState:UIControlStateNormal];
但是UIImage
来到标题之前。有人能指出我出错的地方吗?
答案 0 :(得分:1)
替代
UIImageView *imageView1=[[UIImageView alloc]init];
UIButton *dropdownbutton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
dropdownbutton.frame=CGRectMake(50, 50, 120, 50);
imageView1.image=[UIImage imageNamed:@"arrows.png"];
imageView1.frame=CGRectMake(85, 12, 25, 25);
dropdownbutton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
[dropdownbutton addSubview:imageView1];
CGFloat spacing = 10; // the amount of spacing to appear between image and title
dropdownbutton.titleEdgeInsets = UIEdgeInsetsMake(0, spacing, 0, 0);
[dropdownbutton setTitle:@"Your text" forState:UIControlStateNormal];
[self.view addSubview:dropdownbutton];
答案 1 :(得分:0)
有时创建IUButton的子类会使事情变得更容易,因为图像和文本的结构彼此依赖。创建UIButton的子类:
@interface DropDownButton : UIButton
并覆盖实现(.m)文件中的layoutSubviews
方法:
@implementation DropDownButton
- (void)layoutSubviews {
[super layoutSubviews];
//Use the lines below if you have a specific image for the button
//float imageWidth = 67;
//float imageHeight = 25;
UIImageView *imageView = [self imageView];
UILabel *label = [self titleLabel];
CGRect imageFrame = imageView.frame;
CGRect labelFrame = label.frame;
labelFrame.origin.x = (self.frame.size.width * 1) / 3;
labelFrame.size.width = self.frame.size.width;
imageFrame.origin.x = 10;
[label setShadowOffset:CGSizeMake(0, -0.5)];
[label setFont:[UIFont fontWithName:@"Helvetica" size:22.0]];
[label setTextAlignment:UITextAlignmentLeft];
imageView.frame = imageFrame;
label.frame = labelFrame;
}
如果您坚持使用边缘插入,请尝试使用
dropdownbutton.contentMode = UIViewContentModeLeft;
在给予插图之前;它可能有所帮助。