【问题标题】:I'm implementing a UIView subclass with drawRect: how can I draw a button?我正在使用 drawRect 实现 UIView 子类:如何绘制按钮?
【发布时间】:2011-05-22 21:23:16
【问题描述】:

我有一个 UIView 子类,我正在为整个应用程序中常用的小视图制作。我绘制视图的图像和文本没问题,现在我必须向该视图添加 2 个按钮。这样做的正确方法是什么?

【问题讨论】:

    标签: objective-c ios uiview uibutton drawrect


    【解决方案1】:

    任何视图都可以有子视图,即使视图实现了drawRect:。子视图的内容总是覆盖父视图的内容。 UIButton 是一个视图。因此,只需将按钮添加为自定义视图的子视图即可。

    【讨论】:

      【解决方案2】:

      你可以像这样简单地添加它:

      UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
      
      [button setTitle:@"Button title" forState:UIControlStateNormal]; //Set the title for regular state
      [button addTarget:self 
             action:@selector(yourMethod:)
       forControlEvents:UIControlEventTouchDown];
      button.frame = CGRectMake(40, 100, 160, 240); //make the frame
      [view addSubview:button]; //add to current view
      

      虽然已经有几个主题讨论了这个主题,请使用搜索栏。 :)

      【讨论】:

      • 不是在 iOS 上它没有。在 iOS 上,IBActions 可以采用 0、1 或 2 个参数。 (第二个是 UIEvent)
      【解决方案3】:
      //required ...
      UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
      [button setTitle:@"who am i?" forState:UIControlStateNormal];
      [button setFrame:CGRectMake(20, 20, 200, 40)];
      [button addTarget:self action:@selector(performAction) forControlEvents:UIControlEventTouchUpInside];
      
      //optional properties..
      [button setBackgroundColor:[UIColor greenColor]];
      [button setImage:[UIImage imageNamed:@"someImg.png"] forState:UIControlStateNormal];
      [button setBackgroundImage:[UIImage imageNamed:@"green-hdr-bg.png"] forState:UIControlStateNormal];
      [button setImageEdgeInsets:UIEdgeInsetsMake(5, 5, 5, 5)];
      
      [yourCustomView addSubview:button];
      
      
      
      -(void)performAction
      {
          //do you button click task here
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-28
        • 1970-01-01
        • 2012-06-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多