【问题标题】:ACTION for UIBUTTON in iOSiOS 中 UIBUTTON 的操作
【发布时间】:2013-10-05 12:56:07
【问题描述】:

我有一个带有 UIView 子类的自定义类,在其中我动态创建了一个按钮。 现在我想为按钮方法设置动作。我像 UIviewController 一样设置正常。 但它不起作用。

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
    UIButton *but=[UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    but.frame= CGRectMake(200, 15, 15, 15);
    [but setTitle:@"Ok" forState:UIControlStateNormal];
    [but addTarget:self action:@selector(aMethod)
  forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:but];
    // Initialization code
}
return self;
 }

-(void)aMethod
{

    NextEyeViewController *nexteye=[[NextEyeViewController alloc]initWithNibName:@"NextEyeViewController" bundle:nil];
    [self presentViewController:nexteye animated:YES completion:nil];
}

-(void)aMethod 是我的按钮方法名称

【问题讨论】:

  • 在您的自定义 UIView 类中,您可能需要启用 UserInteraction(这是一个您可以设置为 YES / NO 的属性)。
  • 我没有在那里使用 xib 来启用用户交互
  • 没关系。如果我没记错的话,默认情况下 userInteractionEnabled 设置为 NO 用于自定义 UIViews - 可能是出于性能原因。如果您想与视图上的任何控件(按钮等)进行交互,则必须将其显式设置为 YES

标签: ios uiview uibutton


【解决方案1】:

如果您想为以编程方式创建的按钮设置操作,您需要这样做:

UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
[button addTarget:self 
           action:@selector(aMethod)
 forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(0.0, 0.0, 160.0, 40.0);
[view addSubview:button];

【讨论】:

  • 是的,我这样做了,但事情是从一个自定义类(UIview)转移到 uiviewcontroller。
  • 已添加请查看
  • 所以将您的选择器 @selector(buttonAction) 更改为 @selector(aMethod)
  • 确定在单击按钮时没有传入 aMethod 吗?在里面添加断点或者NSLog
【解决方案2】:

创建 UIButton:

UIButton *yourButton = [[UIButton alloc] initWithFrame:frameButton];

// Here code to set button properties: color, label...

[yourButton addTarget:self action:@selector(aMethod) forControlEvents:UIControlEventTouchDown];

[self.view addSubview:yourButton];

【讨论】:

    【解决方案3】:

    你的方法必须接收动作的发送者:

    -(void)aMethod:(id)sender {
       // your code
    }
    

    更新: 您还必须使用 @selector(aMethod:) 而不是 @selector(aMethod) 适当地调用您的方法。

    【讨论】:

    • 无论如何,您的按钮会将其身份传递给您的函数。您可能还有另一个错误,但这仍然是正确的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-31
    • 1970-01-01
    • 1970-01-01
    • 2017-05-05
    • 1970-01-01
    相关资源
    最近更新 更多