xcode 如何在界面生成器中将子视图添加到 UIButton
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13374860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I addSubview to UIButton in Interface Builder
提问by tinln
Like I said, I add a UIButton in Interface Builder, I want add a UILabel、UIImageView as the button's subviews, but I can't add any object on it in IB. IS anybody know how to do this? Thank you very much.
就像我说的,我在Interface Builder中添加了一个UIButton,我想添加一个UILabel、UIImageView作为按钮的子视图,但是在IB中我无法在其上添加任何对象。有人知道怎么做吗?非常感谢。
I can use code to achieve that, but I want achieve it in IB, so I can use it in any class I want.
我可以使用代码来实现它,但我想在 IB 中实现它,所以我可以在我想要的任何类中使用它。
回答by Fogmeister
I have done this before by adding a UIView (instead of the UIButton) then add the UIButton and UILabel to the UIView. The tap from the UIButton still works and you have a label too. You can also add anything else like this.
我之前通过添加 UIView(而不是 UIButton)然后将 UIButton 和 UILabel 添加到 UIView 来完成此操作。UIButton 的点击仍然有效,您也有一个标签。您还可以添加任何其他类似内容。
回答by Dave Carpenter
I normally achieve this by
我通常通过
- Create a new UIView in Interface Builder and set it to be the same size and location that you want your button to have
- Add your subviews to that UIView
- Set the UIView's class to UIButton in the Indentity Inspector
- 在 Interface Builder 中创建一个新的 UIView 并将其设置为您希望按钮具有的相同大小和位置
- 将您的子视图添加到该 UIView
- 在 Indentity Inspector 中将 UIView 的类设置为 UIButton
Your UIView now works exactly like a UIButton
你的 UIView 现在就像一个 UIButton
回答by Mhdali
instead of UIButton, add the UILabel and UIImageView to UIView and then add a tap action to it.
代替 UIButton,将 UILabel 和 UIImageView 添加到 UIView,然后向其添加点击操作。
EDIT 1:
编辑 1:
it's easy to change make a highlighted color effect, use the following code:
很容易改变使突出显示的颜色效果,使用以下代码:
- (void) onViewTap:(id)sender
{
[UIView animateWithDuration:0.1
delay:0
options:UIViewAnimationOptionCurveEaseOut
animations:^{
_view.backgroundColor = [UIColor blueColor];
}
completion:^(BOOL finished){
_view.backgroundColor = [UIColor whiteColor];
}];
//write tap actions below
}
- (void)viewDidLoad
{
_view.userInteractionEnabled = YES;
UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onViewTap:)];
[_view addGestureRecognizer:tap];
}
回答by Apple Developer
Make your UIButton custom button, then add the UILabel on it,then the you will benefit from the UIButton properties and actions,hope this help you
制作您的 UIButton 自定义按钮,然后在其上添加 UILabel,然后您将从 UIButton 属性和操作中受益,希望这对您有所帮助