[英]iOS touching a UIImageView
- (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時,我期望觸摸功能會達到touchedview == focus的條件。 但是,我無法激活該條件? 怎么了?
請啟用
main_im0.userInteractionEnabled = YES;
默認情況下, UIImageView
為No
傑森(Jason),也許我在誤解您的代碼,但是您是否不打算在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];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.