在下面的代码中,我想在控制台上显示每个按钮的标签。我尝试过,但它超出了范围。怎么样?
- (void)loadView {
[super loadView];
self.view.backgroundColor = [UIColor redColor];
UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
scroll.pagingEnabled = YES;
NSInteger numberOfViews = 33;
[btnMenu setTag:0 ];
for (int i = 1; i < numberOfViews; i++) {
CGFloat yOrigin = i * self.view.frame.size.width;
UIView *awesomeView = [[UIView alloc] initWithFrame:CGRectMake(yOrigin, 0, self.view.frame.size.width, self.view.frame.size.height)];
//awesomeView.backgroundColor = [UIColor colorWithRed:0.5/i green:0.5 blue:0.5 alpha:1];
btnMenu = [UIButton buttonWithType:UIButtonTypeCustom];
//NSData *data =UIImageJPEGRepresentation(, 1);
[btnMenu setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"page-%d.jpg",i]] forState:UIControlStateNormal];
CGRect frame = btnMenu.frame;
frame.size.width=320;
frame.size.height=460;
frame.origin.x=0;
frame.origin.y=0;
btnMenu.frame=frame;
[btnMenu setTag:i];
btnMenu.alpha = 1;
[btnMenu addTarget:self action:@selector(btnSelected:) forControlEvents:UIControlEventTouchUpInside];
[awesomeView addSubview:btnMenu];
[scroll addSubview:awesomeView];
[awesomeView release];
}
scroll.contentSize = CGSizeMake(self.view.frame.size.width * numberOfViews, self.view.frame.size.height);
[self.view addSubview:scroll];
[scroll release];
}
-(IBAction)btnSelected:(id)sender{
switch (btnMenu.tag) {
NSLog(@"%d",btnMenu.tag);
}}
答案 0 :(得分:3)
试试这个:
-(IBAction)btnSelected:(id)sender{
UIButton *button = (UIButton *)sender;
int whichButton = button.tag;
NSLog(@"Current TAG: %i", whichButton);
}
修改强>
你真的需要这个方法作为IBAction方法吗?
你不能把它当作一个无效的吗?
-(void)btnSelected:(id)sender{
UIButton *button = (UIButton *)sender;
int whichButton = button.tag;
NSLog(@"Current TAG: %i", whichButton);
}
答案 1 :(得分:1)
-(IBAction)btnSelected:(id)sender{
UIButton* btnMenu = (UIButton*)sender;
switch (btnMenu.tag) {
NSLog(@"%d",btnMenu.tag);
}
}
答案 2 :(得分:0)
尝试将此代码作为您的操作方法
-(IBAction)btnSelected:(id)sender{
switch (sender.tag) {
NSLog(@"%d",sender.tag);
}}
这将打印所选当前按钮的标签。
TNQ
答案 3 :(得分:0)
创建按钮时,在本地创建它(在for循环中),否则它将只包含最后一个标记。
totalNoOfImages=32;
为:
for(int i=0;i<totalNoOfImages;i++)
{
UIButton *button=[[[UIButton alloc] initWithFrame:CGRectMake(i*50,0,45,44)] autorelease];
//SETTING TAG FOR IMAGE
[button setTag:i];
[button addTarget:self action:@selector(btnSelected:)forControlEvents:UIControlEventTouchDown];
[scrollView addSubview:iconImageSlide];
}
以下方法将显示标记:
- (void) btnSelected:(id)sender
{
int btnId=[(UIButton *)sender tag];
NSLog(@"btnTag= %d", ibtnId)
}
答案 4 :(得分:0)
-(IBAction)btnSelected:(id)sender{
UIButton *btnSelected = sender;
NSLog(@"%d",btnSelected.tag);
}
上面的代码对我有用,它在日志中打印标记值。你必须做错事。