Utilisez un UIButton.
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
[aButton setImage:someUIImage forState:UIControlStateNormal];
[aButton addTarget:self action:@selector(aMethod) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:aButton];
alternative à UIButton (méthode plus)
A UIControl
met en oeuvre des interactions de l'utilisateur et le support pour les interactions des utilisateurs à grains fins déjà. Vous pouvez combiner les fonctionnalités d'un UIImageView
et d'un UIControl
pour y parvenir puisque les deux sont des sous-classes de UIView
. Pour obtenir ce comportement, ajoutez un objet de UIImageView en tant que sous-vue à un UIControl
afin que l'image soit entièrement couverte. Ajoutez ensuite un gestionnaire d'événements à ce contrôle en utilisant addTarget:action:forControlEvents:
. Voici un exemple:
// assuming the image view object exists
UIImageView *anImageView = ..;
// create a mask that the covers the image exactly
UIControl *mask = [[UIControl alloc] initWithFrame:anImageView.frame];
// add the image as a subview of this mask
CGSize imageSize = anImageView.frame.size;
anImageView.frame = CGRectMake(0, 0, imageSize.width, imageSize.height);
[mask addSubview:anImageView];
// add a target-action for the desired control events to this mask
[mask addTarget:self action:@selector(someMethod:) forControlEvents:UIControlEventTouchUpInside];
// add the mask as a subview instead of the image
[self.view addSubview:mask];
Par TouchDown, voulez-vous dire 'UIControlEventTouchDown'? – Anurag
oui je veux dire UIControlEventTouchDown –