UIButton标题和图像对齐查询

sia*_*asl 28 iphone cocoa-touch uibutton

我有一个UIButton,我正在尝试设置标题和图像.

我想将a的标题UIButton与左侧对齐,并将图像对齐到右侧.我试图在Timer in Clocks应用程序中显示按钮的外观和感觉(显示"当计时器结束时").

我摆弄contentHorizontalAlignment,contentEdgeInsets,titleEdgeInsetsimageEdgeInsets达到我的目标,但无济于事.同样的文档也很稀疏.

我怎样才能实现同样的目标?

还有相关问题,Timer in Clocks应用程序有两组文本,一组与左侧对齐,另一组与图像对齐?怎么能在一个UIButton?(我现在不需要那个功能).

ing*_*ham 49

这是我用于的代码:

//Right-align the button image
CGSize size = [[myButton titleForState:UIControlStateNormal] sizeWithFont:myButton.titleLabel.font];
[myButton setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, -size.width)];
[myButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, myButton.imageView.image.size.width + 5)];
Run Code Online (Sandbox Code Playgroud)

  • 如果你将`contentHorizo​​ntalAlignment`设置为`UIControlContentHorizo​​ntalAlignmentRight`,你还需要在`titleEdgeInsets`的左边添加一个插图.这是:`[myButton setTitleEdgeInsets:UIEdgeInsetsMake(0,-imageSize.width,0,imageSize.width)];` (3认同)

Bil*_*ill 35

更改imageEdgeInsets属性UIButton,然后使用setImage:forState:

  • 同意,但OP没有提到表格视图:) (5认同)

小智 14

以下代码有效:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = buttonRect;
[button setTitle:@"A title" forState:UIControlStateNormal];
[button setImage:buttonImage forState:UIControlStateNormal];
button.imageEdgeInsets = UIEdgeInsetsMake(0.0, WIDTH(button.titleLabel) + 10.0, 0.0, 0.0);
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
Run Code Online (Sandbox Code Playgroud)


Tim*_*Tim 9

请记住,UIButton继承自UIView,因此您可以像其他任何视图一样向其添加子视图.在您的情况下,您将创建一个按钮,然后在左侧添加UILabel,在右侧添加UIImage:

// Create the button
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];

// Now load the image and create the image view
UIImage *image = [UIImage imageNamed:@"yourImage.png"];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(/*frame*/)];
[imageView setImage:image];

// Create the label and set its text
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(/*frame*/)];
[label setText:@"Your title"];

// Put it all together
[button addSubview:label];
[button addSubview:imageView];
Run Code Online (Sandbox Code Playgroud)

  • 当背景图像作为自定义视图顶部的UIButton的子视图添加时,通常会出现这种行为.考虑为自己为背景图像添加UIImageView,然后在该图像视图之上添加其他自定义内容,而不是设置按钮的backgroundImage属性. (2认同)