以编程方式创建子视图,然后添加TapGesture For Action

时间:2014-09-09 15:25:08

标签: ios objective-c cocoa-touch

我是PHP背景的初学者。 我想使用FOR循环创建子视图,然后检测哪个子视图被点击,然后执行一些操作。 到目前为止,我已成功使用此代码实现创建子视图:

内部-(IBAction)ADD:(id)sender{

UIScrollView *scrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
[self.view addSubview:scrollview];

float x=0;
float y=0;
float w = 160.0; //width of a box
float h = 100.0; //height of a box
int num = 0;
int totalBoxes = 20;
BOOL yChanged = false; //this is to know if a new line to be added by incrementing y
NSTimeInterval delayTime = 0.1; //for delaying the animation a bit
for(int i=0; i<=totalBoxes; i++){
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(x,y, w, h)];
    view.backgroundColor = [UIColor blueColor];
    view.alpha = 0.0; //initially setting this view to alpha=0 for fadeIn effect
    view.userInteractionEnabled = YES;
    [scrollview addSubview:view];
    delayTime += 0.1; //for delaying the animation a bit
    [UIView animateWithDuration:0.1
                    delay: delayTime
                    options: UIViewAnimationOptionCurveEaseIn
                    animations:^{view.alpha=1.0;}
                    completion:nil]; //performing block animation
    //this is all for detecting where to add the next box...
    if(yChanged){
        num = 1;
        yChanged = false;
    } else {
        num ++;
    }

    x += w+1;
    if(num >= 2){
        y += h+1;
        yChanged = true;
        x = 0;
    }
}
scrollview.contentSize = CGSizeMake(self.view.frame.size.width, (totalBoxes/2)*h);

现在,我不知道在哪里添加Tap Gesture。 我想要的是,当一个盒子被Tapped一次时,我会知道什么盒子是Tapped,这样我就可以从中取出一些信息并在新的子视图上显示(即将所有盒子滑出屏幕,然后显示一个新视图,我将显示从Tapped Box中获取的内容。这更像是一个UITableView,但由于我的设计需要,我不想使用它。)

有什么想法吗?非常感谢,谢谢!

**** **** UPDATE 根据{{​​1}}答案:

我在Owen Hartnett

之前添加了以下代码
[scrollview addSubview:view];

现在,我对如何在UIButton *playButton = [[UIButton init] initWithFrame:CGRectMake(5, 5, 50, 50)]; [playButton setTitle:@"Play" forState:UIControlStateNormal]; [playButton setTitleColor:[UIColor darkTextColor]forState:UIControlStateNormal]; [playButton setEnabled:YES]; [playButton setUserInteractionEnabled:YES]; [playButton addTarget: view action:@selector() forControlEvents: UIControlEventTouchDown]; [view addSubview:playButton]; 内专门为此按钮添加操作感到困惑? 这样每个按钮都会有独特的动作来执行。 请指教,谢谢!

2 个答案:

答案 0 :(得分:1)

将新视图作为子视图添加到滚动视图

后立即将其添加到您的代码中
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = view.frame;
//tag should be > 0
button.tag = i+1;
[button addTarget:self action:@selector(scrollButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
[scrollview addSubview:button];

当然,将此功能添加到您的控制器:

-(void)scrollButtonTapped:(UIButton *)sender
{
   NSInteger scrollViewIndex = sender.tag-1;
}

答案 1 :(得分:0)

有几种方法可以做到这一点。您的视图本质上是按钮,因此您可以轻松地在每个视图上添加一个清晰(不可见)按钮,以响应您的点击。然后你可以使用UIButton的tag属性来知道实际获得了哪个按钮。优点是按钮保持在视图中。如果您觉得必须添加点按手势,则只需在创建视图后随时添加即可。请注意,您将拥有20个手势识别器或20个按钮。就个人而言,我认为按钮更容易管理。