gpt4 book ai didi

ios - 点击作为 UIView subview 的 UIButton

转载 作者:行者123 更新时间:2023-11-29 13:41:48 25 4
gpt4 key购买 nike

我在捕获 UIButton 上的点击时遇到问题,该 UIButtonUIView 的 subview 。以下是我的代码的设置方式:

// 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

按钮出现在 View 中。当我点击它时,按钮颜色会瞬间改变。然而,选择器 buttonTapped: 从未被调用。 知道为什么吗?

我如何验证 buttonTapped: 确实是 myButton 的目标?

最佳答案

您可以通过记录 r 来验证您当前的类是否是目标

NSLog(@"actions for target %@",[myButton actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]);

但是,我将您的代码添加到测试项目(单 View 模板)并且 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?

关于ios - 点击作为 UIView subview 的 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8889279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com