iOS - 将UIView转换为UIButton /其他视图

时间:2013-06-11 06:17:20

标签: ios objective-c uiview uibutton

我将以编程方式创建UIButton和其他视图。这些按钮将在自定义类调用ButtonBuilder中创建。此构建器类将是BaseBuilder类的子类。课程如下所示。

BaseBuilder类

- (id)init{
     self = [super init];
     if (0 != self) {
        baseView = [[UIView alloc]init]; //baseView is a property of BaseBuilder class
     }
     return self;
  }

//Real implementation of build class is more complicated than just setting 
//the background color and frame size
-(void)build{ 
     baseView.backgroundColor = [UIColor clearColor];
     baseView.frame = CGRectMake(0,0,50,50);
 }

ButtonBuilder类

-(void)build:(UIView*) view{ 
     UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
     [super build];
     button = (UIButton*)baseView;
     button.text = @"ButtonText"; // other button settings will be added here

     [view addSubview:button]; // view is view from main view controller
}

我知道在iOS中无法将UIView转换为UIButton。因此,我需要有关投射视图的替代方案的建议。

2 个答案:

答案 0 :(得分:2)

您无法将UIView投射到UIButton。如果你必须做类似的事情尝试创建一个新的按钮实例,只需将视图的所有属性设置为按钮。但我不太了解你想做什么。

-(void)build:(UIView*) view{ 
  [super build];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setFrame:baseView.frame];
[btn setBackgroundColor:view.backgroundColor];
[btn addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
[view addSubview:btn];
}

答案 1 :(得分:1)

您可以在按钮中使用视图,而无需测试代码:

UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 100)];
[view setUserInteractionEnabled:NO];
[view setBackgroundColor:[UIColor redColor]];

UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn addSubview:view];
[btn setFrame:CGRectMake(0, 0, 200, 100)];
[btn addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:btn];