例如,这样的按钮是否可以实现?
我见过像 this 这样的问题他们之前讨论过如何放置它,这确实很容易,但我不完全确定当文本可以是任何东西时如何将它附加到按钮上文本的末尾。从概念上讲,这就像有文本,然后 UIButton 在它的右边说 10pt。
执行此操作的最佳方法是否只是一个带有 UILabel
和 UIImageView
的 UIView
,并附有点击手势识别器?
最佳答案
快速示例:
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *img = [UIImage imageNamed:@"Arrow.png"];
[button setTitle:@"A Button" forState:UIControlStateNormal];
[button setImage:img forState:UIControlStateNormal];
[button sizeToFit];
CGRect imageRect = [button imageRectForContentRect:button.bounds];
CGRect titleRect = [button titleRectForContentRect:button.bounds];
UIEdgeInsets imageInset = UIEdgeInsetsZero;
UIEdgeInsets titleInset = UIEdgeInsetsZero;
titleInset.left = -2 * imageRect.size.width;
imageInset.left = titleRect.size.width;
button.titleEdgeInsets = titleInset;
button.imageEdgeInsets = imageInset;
[self.view addSubview:button];
CGFloat prevHeight = button.frame.size.height;
UIButton *anotherButton = [UIButton buttonWithType:UIButtonTypeCustom];
[anotherButton setTitle:@"Another Button" forState:UIControlStateNormal];
[anotherButton setImage:img forState:UIControlStateNormal];
[anotherButton sizeToFit];
imageRect = [anotherButton imageRectForContentRect:anotherButton.bounds];
titleRect = [anotherButton titleRectForContentRect:anotherButton.bounds];
imageInset = UIEdgeInsetsZero;
titleInset = UIEdgeInsetsZero;
titleInset.left = -2 * imageRect.size.width;
imageInset.left = titleRect.size.width;
anotherButton.titleEdgeInsets = titleInset;
anotherButton.imageEdgeInsets = imageInset;
CGRect frame = anotherButton.frame;
frame.origin.y += prevHeight + 4;
[anotherButton setFrame:frame];
[self.view addSubview:anotherButton];
}
如果你想在标题和图像之间添加空间,你只需要调整按钮大小和内嵌。
关于ios - 是否可以让 UIButton 由文本组成,但最后有图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20314337/