您可以做的一件事是以编程方式将按钮和标签添加到图层。
编辑
好的,我弄清楚了问题所在。当您添加这一行时:[graphic addSublayer:self.btn.layer];
您的应用程序崩溃了,因为您的按钮已经添加到视图层次结构中,因为您使用情节提要创建它。
我所做的是声明一个新标签和按钮而不将其添加到情节提要中(参见注释“A”)。之后,我在方法中实例化了它们viewDidLoad
,然后将它们添加到您创建的图层中。
警告
我在这里显示的这段代码将有效地在顶部显示您的标签和按钮,CALayer
但请记住,CALayer
s 用于绘图和动画,而不是用于用户交互。与 a 不同,UIView
aCALayer
不继承自UIResponder
,因此它无法接收 aUIView
接收的触摸。
但是,有一种解决方法。您可以使用手势识别器来检测用户的触摸和交互,而不是使用 Target-Action 机制。在这个例子中,我添加了一个简单UITapGestureRecognizer
的来说明它是如何完成的。每次点击按钮时,控制台中都会显示“Button Tapped”消息。
// This is the *.m file
#import "ViewController.h"
@interface ViewController ()
// Comment A. Another label and button added to the class without adding them to the
// storyboard
@property (nonatomic, strong) UIButton *firstButton;
@property (nonatomic, strong) UILabel *mylabel;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.firstButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[self.firstButton setTitle:@"Just a Button" forState:UIControlStateNormal];
self.firstButton.frame = CGRectMake(50, 50, 300, 40);
UIGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(theAction:)];
[self.firstButton addGestureRecognizer:tapGesture];
self.mylabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 120, 200, 40)];
self.mylabel.text = @"Hello World";
self.mylabel.backgroundColor = [UIColor cyanColor];
//The screen width and height
CGRect screenBound = [[UIScreen mainScreen] bounds];
CGSize screenSize = screenBound.size;
CGFloat screenWidth = screenSize.width;
CGFloat screenHeight = screenSize.height;
//The CALayer definition
CALayer *graphic = nil;
graphic = [CALayer layer];
graphic.bounds = CGRectMake(0, 0, screenHeight, screenWidth);
graphic.position = CGPointMake(screenHeight/2, screenWidth/2);
graphic.backgroundColor = [UIColor whiteColor].CGColor;
graphic.opacity = 1.0f;
[graphic addSublayer:self.firstButton.layer];
[graphic addSublayer:self.mylabel.layer];
[self.view.layer addSublayer:graphic];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)theAction:(id)sender {
NSLog(@"Button Tapped");
}
@end
如果您有更多问题,请告诉我。
希望这可以帮助!