Ci sono 2 approcci:
primo approccio:
È possibile impostare un tag per la visualizzazione personalizzata:
customview.tag=99;
Una allora nella vostra viewcontroller, utilizzare il touchesBegan:withEvent:
delegato
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
if(touch.view.tag!=99){
customview.hidden=YES;
}
}
Secondo approccio:
E 'più probabile che ogni volta che si desidera popup una visualizzazione personalizzata, c'è una sovrapposizione alle spalle, che riempirà la vostra schermo (es una vista nera con alfa ~ 0.4). In questi casi, puoi aggiungere un UITapGestureRecognizer
e aggiungerlo alla tua visualizzazione ogni volta che vuoi che venga visualizzata la tua visualizzazione personalizzata. Ecco un esempio:
UIView *overlay;
-(void)addOverlay{
overlay = [[UIView alloc] initWithFrame:CGRectMake(0, 0,self.view.frame.size.width, self.view.frame.size.height)];
[overlay setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.5]];
UITapGestureRecognizer *overlayTap =
[[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(onOverlayTapped)];
[overlay addGestureRecognizer:overlayTap];
[self.view addSubview:overlay];
}
- (void)onOverlayTapped
{
NSLog(@"Overlay tapped");
//Animate the hide effect, you can also simply use customview.hidden=YES;
[UIView animateWithDuration:0.2f animations:^{
overlay.alpha=0;
customview.alpha=0;
}completion:^(BOOL finished) {
[overlay removeFromSuperview];
}];
}
suggerirei il primo approccio, piuttosto che usare un controllo non necessario (UITapGestureRecognizer). E soprattutto "Meno codice, più stabile l'app" – DHEERAJ
In questa risposta si lavora al primo approccio sul mio progetto. Ne condividerò la versione veloce –