当按下我创建的按钮时,此代码会导致“无效选择器”错误。从{
>获取test
函数的位置
的main.m
mainScreen = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 768, 1024)];
[self.view addSubview:mainScreen];
TaskButtons *tB = [[TaskButtons alloc] init];
[mainScreen addSubview:[tB TaskStart]];
TaskButtons.m
- (UIButton*)TaskStart {
CGRect buttonFrame = CGRectMake(500, 206, 400, 35);
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = buttonFrame;
[button setTitle:@"Task Button" forState:UIControlStateNormal];
button.backgroundColor = [UIColor clearColor];
button.titleLabel.textAlignment = UITextAlignmentLeft;
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
[button setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
[button addTarget:self action:@selector(test) forControlEvents:UIControlEventTouchUpInside];
return button;
}
- (void)test{
NSLog(@"test line");
}
似乎没有调用test
函数。这里没有将按钮的target
设置为self
意味着它应该在TaskButtons
类中查找名为test
的函数吗?
答案 0 :(得分:0)
问题是ARC过早地释放实例化对象。所以为了解决这个问题,我需要更长时间地保留它。
Main.h
#import "TaskButtons.m"
@interface ViewController : UIViewController {
TaskButtons *tB;
}
@property (nonatomic, retain) TaskButtons *tB;
答案 1 :(得分:0)
[button addTarget:self action:@selector(test:) forControlEvents:UIControlEventTouchUpInside];
- (void)test:(id)sender{
NSLog(@"test line");
}
语法问题:)在你的代码中替换这些行。