【发布时间】:2014-11-18 09:07:34
【问题描述】:
我有一个在我的应用程序的许多屏幕中使用的按钮。我想用自定义图像和按下按钮时的回调来实现一个自定义按钮。
我习惯了 java,但我不知道如何在 iOS 中解决这个问题。我已经阅读过关于 Category 和 Subclassing 的内容,但我仍然不确定。
有人有例子吗?或者什么是最好的解决方案?非常感谢任何帮助。
我做了什么(感谢@Aris):
.h 文件
#import <UIKit/UIKit.h>
@interface UIButton (MyUIButton)
+ (UIButton *)customButtonWithTarget:(id)target;
@end
.m 文件
#import "UIButton+MyUIButton.h"
@implementation UIButton (MyUIButton)
+ (UIButton *)customButtonWithTarget:(id)target{
UIButton *button_ = [UIButton buttonWithType:UIButtonTypeSystem];
[button_ setFrame:CGRectMake(0, 0, 120, 44)];
[button_ setBackgroundImage:[UIImage imageNamed:@"button_image.png"] forState:UIControlStateNormal];
[button_ addTarget:target
action:@selector(event_button_click:)
forControlEvents:UIControlEventTouchUpInside];
return button_;
}
@end
在我的视图控制器中:
#import "UIButton+MyUIButton.h"
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *myButton = [UIButton customButtonWithTarget:self];
[self.view addSubview:myButton];
}
-(void)event_button_click
{
// code here
}
我收到此错误:'-[ViewController event_button_click:]: unrecognized selector sent to instance 0x78e5df10'
【问题讨论】:
-
在xcode中更容易右键单击界面生成器中的按钮并拖动到
标签: ios objective-c callback uibutton custom-controls