- (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的条件。但是,我无法激活那个条件?怎么了?
答案 0 :(得分:4)
请启用
main_im0.userInteractionEnabled = YES;
默认为No
UIImageView
答案 1 :(得分:1)
您可以使用:
// 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];