【问题标题】:iOS - Casting UIView to UIButton/other viewsiOS - 将 UIView 转换为 UIButton/其他视图
【发布时间】:2013-06-11 06:17:20
【问题描述】:

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

【问题讨论】:

    标签: ios objective-c uiview uibutton


    【解决方案1】:

    您不能将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];
    }
    

    【讨论】:

      【解决方案2】:

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

      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];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-03
        • 2021-01-24
        • 2012-02-22
        相关资源
        最近更新 更多