1

我将以编程方式创建 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 。因此,我需要关于替代意见的建议。

4

2 回答 2

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];
}
于 2013-06-11T06:49:20.377 回答
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];
于 2013-06-11T06:25:15.133 回答