将子视图(UIButtons)添加到UIImageView的子类时出现问题

sam*_*u_1 0 iphone cocoa-touch uibutton uiview uiimageview

我正在为我的应用程序添加自定义按钮/键盘.到目前为止,我有一个UIImageView子类,其中包含一个动画,可以从屏幕底部滑动,然后在用户不再需要时向下滑动.但是,我无法将UIButtons添加到此UIImageView中.

由于这是UIView的子类,我试图通过initWithFrame:方法向我的视图添加按钮.(slideDown方法是添加的动画)

在我的UIImageView子类中,我添加了一个UIButton ivar对象:

-(id)initWithFrame:(CGRect)frame {

  if (self = [super initWithFrame: frame]) {
  UIButton *button = [UIButton buttonWithType: UIButtonTypeRoundedRect];
  button.frame = CGRectMake(16.0, 20.0, 50.0, 50.0);
  [button setTitle: @"Go" forState: UIControlStateNormal];
  [button addTarget: self action: @selector(slideDown) forControlEvents: UIControlEventTouchUpInside];
  self.button1 = button;
   [self addSubview: button1];
   NSLog(@"Button added");

}
return self;
}
Run Code Online (Sandbox Code Playgroud)

在我的视图控制器中,我在 - (void)viewDidLoad:方法中实例化我的UIIMageView子类,如下所示:

-(void)viewDidLoad {
//other objects init'ed

ButtonPad *customPad = [[ButtonPad alloc] initWithImage: [UIImage imageNamed: @"ButtonPad.png"]];
customPad.frame = CGRectMake(0.0, 480.0, 320.0, 300.0);
self.buttonPad = customPad;

[self.view addSubview: buttonPad];
[customPad release];  

[super viewDidLoad];
}
Run Code Online (Sandbox Code Playgroud)

我当前的应用程序允许视图从屏幕上下滑动而没有任何问题.但是,按钮永远不会出现.我还尝试通过实例化并将其作为子视图添加到我的视图控制器文件中的buttonPad,将按钮添加到我的buttonPad对象.这有效...但它不允许按钮起作用.

我想知道:A.)是否适合向UIView initWithFrame:方法添加按钮或任何子视图,或者我应该将这些子视图作为子视图添加到视图控制器文件中的buttonPad?B.)因为我正在创建一个自定义按钮/键盘,我是通过使用普通的UIViewController遵循有效的方法还是我应该使用像模态视图控制器?(我对这些知之甚少.)

Lau*_*ack 7

我认为你的问题是UIImageView默认禁用了userInteractionEnabled属性.您可以尝试将该行添加
customPad.userInteractionEnabled = true;
到初始化并进行设置.