我有一个类CustomView
(UIView
没有 xib 文件的子类),我正在其中创建一些标签和按钮。我想在另一个类中使用这个类UIViewController
来添加这些标签和按钮。我可以使用自定义视图将标签和按钮添加到我的 viewController,但是如果我向按钮(在自定义视图中)添加一些操作或事件,它就不起作用。请建议我应该怎么做才能为按钮添加操作。
//ViewController code
CustomView *slider=[[CustomView alloc]init];
[self.view addSubview:slider];
//CustomView code
toggleButton = [UIButton buttonWithType:UIButtonTypeCustom];
[toggleButton setTitle:@"" forState:UIControlStateNormal];
toggleButton.userInteractionEnabled=YES;
// add drag listener
[toggleButton addTarget:self action:@selector(wasDragged:withEvent:)
forControlEvents:UIControlEventTouchDragInside];
// center and size
toggleButton.frame = CGRectMake(frame.origin.x, frame.origin.y, width, frame.size.height);
toggleButton.backgroundColor=[UIColor colorWithRed:0.1 green:0.1 blue:0.0 alpha:0.1];
[toggleButton.layer setBorderWidth:4.0];
[toggleButton.layer setBorderColor:[[UIColor lightGrayColor] CGColor]];
toggleButton.layer.cornerRadius=4.0;
[toggleButton setTitleColor:[UIColor colorWithRed:0.3 green:0.1 blue:0.4 alpha:1.0] forState:UIControlStateNormal];
// add it, centered
[self addSubview:toggleButton];
- (void)wasDragged:(UIButton *)button withEvent:(UIEvent *)event
{
NSLog(@"inside drag");
}