【问题标题】:Programmatically code UIButton action以编程方式编写 UIButton 操作
【发布时间】:2013-02-09 20:29:01
【问题描述】:

我正在尝试创建一个按钮,一旦点击该按钮将显示另一个 UIView 的弹出窗口。为了测试这一点,我在 viewDidLoad 部分中有以下代码:

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.hard1 = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.hard1 setFrame:CGRectMake(884, 524, 105, 60)]; // set the x,y,width and height based on your specs
    UIImage *buttonImage = [UIImage imageNamed:@"green.jpg"];
    hard1.layer.cornerRadius = 10;
    hard1.clipsToBounds = YES;
    [hard1 addTarget: self
              action: @selector(buttonClicked:)
    forControlEvents: UIControlEventTouchUpInside];
    [self.hard1 setImage:buttonImage forState:UIControlStateNormal];
    [self.view addSubview:self.hard1];
}

再往下:

- (IBAction) buttonClicked: (id)sender
{
    NSLog(@"Tap");
}

但是,当我点击按钮时,控制台不会记录“Tap”。有什么想法吗?

【问题讨论】:

标签: iphone ios objective-c ipad uibutton


【解决方案1】:
    self.hard1 = [UIButton buttonWithType:UIButtonTypeCustom];


 [hard1 addTarget: self
              action: @selector(buttonClicked:)    forControlEvents: UIControlEventTouchUpInside];

将 hard1 替换为 self.hard1

【讨论】:

    【解决方案2】:

    看这三行代码:

    hard1.layer.cornerRadius = 10;
    hard1.clipsToBounds = YES;
    [hard1 addTarget: self
              action: @selector(buttonClicked:)
    forControlEvents: UIControlEventTouchUpInside];
    

    你失去了自我。在所有三个。它们应该是:

    self.hard1.layer.cornerRadius = 10;
    self.hard1.clipsToBounds = YES;
    [self.hard1 addTarget: self
              action: @selector(buttonClicked:)
    forControlEvents: UIControlEventTouchUpInside];
    

    另外,如果您以编程方式创建它,它不应该是 IBAction(IB 代表界面构建器,它不是在界面构建器中创建的)。

    【讨论】:

    • 现在我已经开始了。当您创建属性时,请在综合中执行此操作:@synthesize hard1 = _hard1;这种将属性称为“hard1”的方式是行不通的。要么是self.hard1要么是_hard1(后者只在setter方法中使用)
    【解决方案3】:

    您已将事件响应者设为buttonClicked,但在IBAction 中您已定义buttonTap。这显然行不通……

    应该是

    [hard1 addTarget: self
                  action: @selector(buttonTap:)
        forControlEvents: UIControlEventTouchUpInside];
    

    【讨论】:

    • 我打错了。我的实际代码在上面编辑过,还是不行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-28
    • 2012-02-13
    相关资源
    最近更新 更多