0
  - (void)viewDidLoad
 {
  [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
   container = [[UIView alloc] initWithFrame:self.view.frame];
UIImageView* main_im0 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon1.png"]];
[container addSubview:main_im0];
[self.view addSubview:container];

 }

 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *tt = [touches anyObject];

UIImageView *touchedview=(UIImageView*)[tt view];


NSArray *views = [container subviews];



 for (UIImageView* im in views)
 {
    UIImageView* focus=im;
    if (touchedview==focus)
    {

    }

}

}

我有这段代码设置了一个名为 main_im0 的 ImageView,它被放入 UIView 容器中,然后放入视图中。当我在 main_im0 上单击时,我希望触摸功能会达到 touchview==focus 的条件。但是,我无法激活该条件?怎么了?

4

2 回答 2

4

请启用

main_im0.userInteractionEnabled = YES;

默认情况下它是NoUIImageView

于 2012-08-16T06:40:01.113 回答
1

杰森,也许我误解了你的代码,但你不是要绕一圈在 UIView 上实现点击手势吗?

您可以使用:

// enable user interaction with this view
main_img0.userInteractionEnabled = YES;

// setup a tap gesture to call a method once triggered (like a javascript mouseClick event)
UITapGesture *tapGesture = [[UITapGesture alloc] initWithTarget:self selector:@selector(myMethodToDoSomething)];

[main_img0 addGestureRecognizer:tapGesture];

// if you are not using Automatic Reference Counting, then remember to release your allocated tapGesture object
[tapGesture release];


...somewhere later in your code....


// method to do something
-(void)myMethodToDoSomething
{
    NSLog(@"This method executed");
}

现在,当您点击 main_img0 视图时,方法“myMethodToDoSomething”将执行

顺便说一句,如果您只想要一个带有您自己的 Photoshop 设计图像的自定义外观按钮,您可以简单地使用代码创建一个 UIButton 并设置 UIButton 的背景图像属性。像这样:

UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 50)];
[button setImage:[UIImage imageNamed:@"mybutton.png"] forControlState:UIControlStateNormal];
于 2012-08-16T07:13:25.940 回答