我想为每个创建的按钮引发一个不同的方法.我尝试在viewDidLoad中调用"FirstImage"方法,但它不起作用.
我在ViewDidLoad中的选择器有问题.没有识别"FirstImage"这是一个没有参数的void方法.
ViewController.m
- (void)createFirstButton:(NSString *)myName: (SEL *)myAction{
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn addTarget:self
action:@selector(myAction)
forControlEvents:UIControlEventTouchUpInside];
[btn setTitle:myName forState:UIControlStateNormal];
btn.frame = CGRectMake(20, 916, 120, 68);
[self.view addSubview:btn];
}
- (void)viewDidLoad{
[self createFirstButton:@"First" myAction:[self FirstImage]];
}
Run Code Online (Sandbox Code Playgroud)
我做了什么(我将"CreateFirstButton"更改为"CreateButton"):
ViewControler.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize myHeight;
@synthesize myWidth;
@synthesize myX;
@synthesize myY;
- (void)createButton:(NSString *)myName:(SEL)myAction:(NSUInteger)my_x:(NSUInteger)my_y:(NSUInteger)my_width:(NSUInteger)my_height
{
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn addTarget:self
action:myAction
forControlEvents:UIControlEventTouchUpInside];
[btn setTitle:myName forState:UIControlStateNormal];
btn.frame = CGRectMake(my_x, my_y, my_width, my_height);
[self.view addSubview:btn];
}
- (void)myXcrementation{
myX = myX + 150;
}
- (void)viewDidLoad{
myX = 20; myY = 916; myWidth = 120; myHeight = 68;
[self createButton:@"First":@selector(FirstImage):myX:myY:myWidth:myHeight];
[self myXcrementation];
[self createButton:@"Previous":@selector(PreviousImage):myX:myY:myWidth:myHeight];
[self myXcrementation];
[self createButton:@"Pause":@selector(PauseImage):myX:myY:myWidth:myHeight];
[self myXcrementation];
[self createButton:@"Next":@selector(NextImage):myX:myY:myWidth:myHeight];
[self myXcrementation];
[self createButton:@"Last":@selector(LastImage):myX:myY:myWidth:myHeight];
}
- (void)FirstImage{
current = 0;
[self SetImage];
}
-(void)SetImage{
[myImageView setImage: [myArray objectAtIndex:(current)]];
}
@end
Run Code Online (Sandbox Code Playgroud)
ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController{
}
@property(assign, nonatomic) NSUInteger myHeight;
@property(assign, nonatomic) NSUInteger myWidth;
@property(assign, nonatomic) NSUInteger myX;
@property(assign, nonatomic) NSUInteger myY;
@end
Run Code Online (Sandbox Code Playgroud)
我再次编辑了这篇文章,没有更多的错误.特别感谢大家.我花时间了解:)
Gab*_*lla 22
您必须@selector按如下方式使用
[self createFirstButton:@"First" myAction:@selector(FirstImage)];
Run Code Online (Sandbox Code Playgroud)
那你的签名是错的,因为SEL不应该是指针.
更改
- (void)createFirstButton:(NSString *)myName: (SEL *)myAction{
Run Code Online (Sandbox Code Playgroud)
至
- (void)createFirstButton:(NSString *)myName: (SEL)myAction{
Run Code Online (Sandbox Code Playgroud)
最后myAction有类型,SEL所以你可以直接将它传递给UIButton方法,如下所示
[btn addTarget:self
action:myAction
forControlEvents:UIControlEventTouchUpInside];
Run Code Online (Sandbox Code Playgroud)
此外,我想补充一点,使用大写的名称方法,这是一个非常糟糕的做法.