关于presentViewController的后的background变黑的问题

本文详细介绍了在iOS应用中遇到模态窗口背景透明度无法正常显示的问题,通过分析原因并提供解决方案,成功实现了背景半透明效果。通过使用UIView动画替代presentModalViewController方法,并设置view的alpha值,解决了背景颜色变为黑色的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先看一下效果图:

用如下代码,想弹出一个模态窗口,设置它的背景透明度为0.5,却发觉prsent后的背景色变为黑色的。

[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. ShareVC *share = [[ShareVC alloc] init];  
  2. [self presentViewController:share animated:YES completion:nil];  

起初还以为是设置透明度或者是[UIColor clearColor]出的问题,鼓捣几次之后发现不是这个问题。google之后,在stackOverflow上找到几个比较靠谱的答案~

Why Does presentModalViewController:animated: Turn The Background Black?

Display clearColor UIViewController over UIViewController

最终结论为:

NavigationController and the View Controllers are designed in such a way that only one view controller may show at a time. When a new view controller is pushed/presented the previous view controller will be hidden by the system. So when you reduce the modal view's alpha you will possibly see the window's backgroundColor (the black color you see now).

If you want a translucent view to slide-in over the main view, you can add the view as the subView of main view and animate it using UIView Animations.

所以还是改用为 UIView Animations 实现:

[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. if (!_isShareViewOpen) {  
  2.    
  3. _isShareViewOpen = YES;  
  4.    
  5. ShareVC *shareVC = [[ShareVC alloc] initWithNibName:@"ShareVC" bundle:nil];  
  6.    
  7. shareVC.shareVC = shareVC;  
  8.    
  9. shareVC.awardList = self;  
  10.    
  11. [self.view addSubview:shareVC.view];  
  12.    
  13. [UIView animateWithDuration:0.75f animations:^{  
  14.    
  15. shareVC.view.frame = CGRectMake(0640self.view.frame.size.widthself.view.frame.size.height);  
  16.    
  17. shareVC.view.frame = CGRectMake(00self.view.frame.size.widthself.view.frame.size.height);  
  18.    
  19. } completion:^(BOOL finished) {  
  20.    
  21. }];  
  22.    
  23. }  



----------------------------------------------------------------------2014.09.26 再次编辑 ------------------------------------------------------------------

如果你不想用动画来实现 present 的效果,可以设置 presentViewController 的属性,一样可以达到以上效果:

[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. presentingViewController.modalPresentationStyle = UIModalPresentationOverCurrentContext;  


原文地址:http://blog.youkuaiyun.com/chaoyuan899/article/details/38390507

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值