如何在iphone手指触摸上获取x和y位置后设置ImageView的位置

时间:2013-07-04 09:31:06

标签: ios ipad touch imageview

我正在制作一个ipad应用程序,其中我有自定义的tableView它工作正常但我希望当用户点击自定义单元格中的添加按钮然后它应该获取该按钮的位置x和y然后将imageView设置为那个按钮的中心。

我有搜索到的代码,但是如果单元格是自定义的,如何为cell.addButton添加make。

        [cell.imageButton addTarget:self action:@selector(imageButtonActionOne:) forControlEvents:UIControlEventTouchUpInside];
    [cell.addButton addTarget:self action:@selector(imageButtonAction:) forControlEvents:UIControlEventTouchUpInside];

以下是触摸的代码

    UITapGestureRecognizer *rec = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapRecognized:)];
   [cell.addButton addGestureRecognizer:rec];
    [rec release];

但是这样它就不会调用cell.addButton上的方法imageButtonAction。

2 个答案:

答案 0 :(得分:1)

据我了解,您需要在点击时在UIButton中设置图像。

如果您添加了UITapGestureRecognizer,则删除了默认的点按识别功能,现在只有这样才能使用:

 UITapGestureRecognizer *rec = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapRecognized:)];
[cell.addButton addGestureRecognizer:rec];
[rec release]; 

你应该删除上面的代码并且只设置它:

[cell.addButton addTarget:self action:@selector(imageButtonAction:) forControlEvents:UIControlEventTouchUpInside];

imageButtonAction:是:

- (void )imageButtonAction:(UIButton *) b
{
 [b setImage:[UIImage imageNamed:@"img.png"] forState:UIControlStateNormal];
}

如果你想在按钮旁边添加一个图像,让我们在按钮的左边说,那么这个函数应该是这样的:

- (void )imageButtonAction:(UIButton *) b
{
 UITableViewCell *cell = (UITableViewCell*)[b superview]; 
 NSInteger imgWidth = 50;
 UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(b.frame.origin.x - imgWidth,b.frame.origin.y,imgWidth,b.frame.size.height)];
img.backgroundColor = [UIColor redColor];
[cell addSubview:img];
[img release];

}


       UIButton *btn = (UIButton *)sender;
UIImageView *backimage = [[UIImageView alloc] initWithFrame:CGRectMake(10,0,312,105)];

//If you want to do this set interaction enabled.
backimage.userInteractionEnabled = YES;
backimage.image=[UIImage imageNamed:@"popupj.png"];



tab1 = [UIButton buttonWithType:UIButtonTypeCustom];
[tab1 setFrame:CGRectMake(-1,2,293,58)];
[tab1 setTitle:@"Record Video" forState:UIControlStateNormal];
[tab1 addTarget:self action:@selector(tab1Action) forControlEvents:UIControlEventTouchUpInside];
[tab1 setImage:[UIImage imageNamed:@"popuptab1j.png"] forState:UIControlStateNormal];

[backimage addSubview:tab1];

现在我正在向imageView添加按钮,但它没有被点击

答案 1 :(得分:0)

对于UIButton,您可以直接使用按钮功能

-(IBAction) imageButtonAction:(id) sender
{
  UITableViewCell *cell = (UITableViewCell *)[[sender superview] superview];
  UIButton *btn = (UIButton *)sender;
  //[btn setimage:[UIImage imagenamed:dimagename];
  UIImageview *backimage = [[UIImageView alloc] initWithFrame:btn.frame];
  [cell addSubview:backimage];
}       
相关问题