【问题标题】:How to create UIButton and its @selector in a NSObject如何在 NSObject 中创建 UIButton 及其 @selector
【发布时间】:2016-12-30 06:08:09
【问题描述】:

我正在尝试生成一个可以创建 UIButton 的类,并处理在按钮所在的任何视图中按下按钮时会发生什么。这是我正在做的事情:

头文件:

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface CreateButton : NSObject

- (UIButton *)createButton;

@end

实施:

#import "CreateButton.h"

@implementation CreateButton

- (UIButton *)createButton
{
    // Instanciate the class
    CreateButton *classInstance = [[CreateButton alloc] init];

    UIButton *testButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 50.0, 50.0)];
    [testButton setBackgroundColor:[UIColor redColor]];
    [testButton addTarget:classInstance action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    return testButton;
}

- (void)buttonClicked:(UIButton *)sender
{
    NSLog(@"Clicked");
}

@end

最后,在视图控制器中,我初始化类并获得按钮:

CreateButton *create = [[CreateButton alloc] init];
UIButton *testButton = [create createButton];
[self.view addSubview:testButton];

到目前为止一切正常,我可以看到按钮,但是当我单击它时没有任何反应。令人惊讶的是,如果我将 buttonClicked: 方法移动到我的视图控制器,它就可以正常工作。我需要将所有按钮接线保留在 NSObject 中。任何帮助将不胜感激。

【问题讨论】:

    标签: objective-c xcode uibutton nsobject


    【解决方案1】:

    好的,我解决了这个问题,有趣。

    实现文件修改为:

    - (UIButton *)createButton
    {
        UIButton *testButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 50.0, 50.0)];
        [testButton setBackgroundColor:[UIColor redColor]];
        [testButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        return testButton;
    }
    

    然后,在视图控制器中,CreateButton 类必须在头文件@interface 部分中预定义。然后在实现中:

    create = [[CreateButton alloc] init];
    

    它有效!如果您能向我解释一下,那就太好了。

    【讨论】:

    • 你不需要创建一个新的createButton实例。你可以只使用 self 因为它指向同一个目标。 classInstance = 自我
    • 你完全正确!我编辑了答案并感谢您的评论。你有没有机会知道为什么对象必须预先定义然后初始化?
    • 您在那里预定义它,因为您希望导入您的类的每个人都能够访问该方法。初始化将取决于程序员其实例方法或类方法(即-(UIButton *)createButton+(UIButton *)createButton
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 1970-01-01
    • 2011-08-05
    相关资源
    最近更新 更多