淡出與淡入是 iOS 介面中常見的過場效果,能讓元素的出現與消失更為柔和。實作起來其實很簡單,只要透過 UIView 的動畫方法,在動畫區塊中改變視圖的 alpha(透明度)值即可。以下程式碼分別示範淡出與淡入:
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. //UIView UIView *view=[[UIView alloc]initWithFrame:CGRectMake(10, 100, 100, 200)]; view.backgroundColor=[UIColor redColor]; [self.view addSubview:view]; //淡出 //[self fadeOut:view]; //淡入 //[self fadeIn:view]; } //淡出 -(void) fadeOut:(UIView *)view { CGContextRef context = UIGraphicsGetCurrentContext(); [UIView beginAnimations:nil context:context]; [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; [UIView setAnimationDuration:0.3]; [view setAlpha:0.0f]; [UIView commitAnimations]; } //淡入 -(void) fadeIn:(UIView *)view { CGContextRef context = UIGraphicsGetCurrentContext(); [UIView beginAnimations:nil context:context]; [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; [UIView setAnimationDuration:0.3]; [view setAlpha:1.0f]; [UIView commitAnimations]; } 關鍵在於 setAnimationDuration 控制動畫持續時間、setAnimationCurve 設定動畫的加減速曲線(這裡採用 EaseInOut 讓效果更自然),而淡出是把 alpha 設為 0.0f、淡入則是設為 1.0f。透過 beginAnimations 與 commitAnimations 把這些設定包成一段完整動畫即可。