攻丝UIButton,这是UIView的子视图
问题描述:
我在UIButton
上捕获水龙头时遇到问题,这是UIView
的子视图。以下是我的代码设置方法:攻丝UIButton,这是UIView的子视图
// in MyClass.m
@interface MyClass()
@property (nonatomic, retain) UIButton *myButton;
@end
@implementation MyClass
@synthesize myButton;
- (void) buttonTapped:(id) sender {
NSLog(@"button tapped!");
}
- (id) initWithFrame:(CGRect)frame {
if (!(self = [super initWithFrame:CGRectZero]))
return nil;
myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[myButton setImage:[UIImage imageNamed:@"image.png"]
forState:UIControlStateNormal];
[myButton addTarget:self
action:@selector(buttonTapped:)
forControlEvents:UIControlEventTouchUpInside];
myButton.exclusiveTouch = YES;
myButton.frame = CGRectMake(100, 100, 100, 100);
[self addSubview:myButton];
return self;
}
- (void) dealloc {
[myButton release];
[super dealloc];
}
@end
该按钮出现在视图中。当我点击它时,按钮颜色会立即改变。然而,选择器buttonTapped:
永远不会被调用。 任何想法为什么?
如何验证buttonTapped:
确实是myButton的目标?
答
你可以检验当前类是目标登录将R
NSLog(@"actions for target %@",[myButton actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]);
不过,我加你的代码的测试项目(单个视图模板)和buttonTapped:
方法处理。
- (void) buttonTapped:(id) sender {
NSLog(@"button tapped!");
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
self.window.rootViewController = self.viewController;
UIButton * myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[myButton setImage:[UIImage imageNamed:@"image.png"]
forState:UIControlStateNormal];
[myButton addTarget:self
action:@selector(buttonTapped:)
forControlEvents:UIControlEventTouchUpInside];
myButton.exclusiveTouch = YES;
myButton.frame = CGRectMake(100, 100, 100, 100);
[rv.view addSubview:myButton];
return YES;
}
该问题在其他地方。代码是否发布了MyClass的整个.h和.m文件?
+0
在这里找到解决方案:http://*.com/questions/3344341/uibutton-inside-a-view-that-has-a-uitapgesturerecognizer。这与使用UIGestureRecognizers有关。 – SundayMonday 2012-01-17 03:53:35
为什么框架被设置为CGRectZero?此外,它应该是'[super dealloc]'而不是'[super release]'。 – Anna 2012-01-17 03:37:27
你是对的。更新为'[super dealloc];' – SundayMonday 2012-01-17 03:39:02