如何为登录设置半透明50%的父UIView?

5

我有一个视图,里面有一个登录按钮。当点击该按钮时,我会添加一个包含登录字段的视图。在此期间,我需要将父视图变暗。如何实现呢?


哇...需要比这更多的信息...你正在使用哪些类?你所说的“调暗...视图”具体是什么意思? - GarlicFries
3
我会添加一个带有50%透明度黑色背景的视图,然后把另一个视图放在里面,该视图具有我想要显示的背景颜色,并且包含文本字段、标签等内容。 - user684934
@Gerep,很高兴能帮到你,但是以后你需要更清楚地表达你的需求,才能得到真正的答案...我只是在胡乱猜测。 - user684934
这里使用模态视图控制器是否合适?请参阅苹果的iOS视图控制器编程指南:模态视图控制器。 - ditkin
@ditkin:可能不行,模态视图控制器无法以有用的方式(部分)透明。如果您选择使模态视图控制器内部的视图(部分)透明,则会看到白色背景。 - Wolfgang Schreurs
4个回答

14

UIViews有一个名为mask的属性。

mask将始终位于拥有它的UIView的顶部。

所以,你的方法应该像这样:

(这是使用Swift编写的,但可以轻松转换为Obj-c)

self.view.mask = UIView(frame: self.frame)
self.view.mask?.backgroundColor = UIColor.black.withAlphaComponent(0.5)

//Do your work here, block UI, anything you need to, and then...
self.view.mask = nil

更新

  • 移除了对Swift 2的引用,因为它已经不再相关。只是作为一个好奇心,那时这个属性被称为maskView

9
在父视图上添加一个初始透明、背景颜色为黑色的UIView。当你需要将其变暗时,将视图的alpha值改为0.5,这将使它变为50%透明。

随着这个问题持续受到关注,请记住目前这个答案并不是最佳选择,它会给视图层次结构增加更多复杂性,需要额外的努力,并且可能引入自动布局问题,也可能存在性能问题。UIView层次结构已经有一个相应的属性。 - Hugo Alonso

4

I would go for a view with white background:

whiteView=[[UIView alloc]initWithFrame:viewToDim.frame];
[whiteView setBackgroundColor:[UIColor whiteColor]];
[whiteView setAlpha:0.5f];
[self.view insertSubview:whiteView aboveSubview:viewToDim];


0
class UIDecorator: NSObject {

    static let sharedInstance = UIDecorator()
    private let dimView = UIView()
    private let loadingView = MOOverWatchLoadingView(frame: CGRectMake(0, 0, 100, 100),
                                                             autoStartAnimation: true)
    func showLoadingView() {
        if let currentPage = UIApplication.topViewController(){
            dimView.frame = currentPage.view.frame
            dimView.backgroundColor = UIColor.blackColor()
            dimView.alpha = 0.5
            currentPage.view.addSubview(dimView)
            currentPage.view.userInteractionEnabled = false
            loadingView.center = currentPage.view.center
            loadingView.backgroundColor = UIColor.clearColor()
            currentPage.view.addSubview(loadingView)
        }
    }

    func dismissLocadingView() {
        if let currentPage = UIApplication.topViewController(){
            currentPage.view.userInteractionEnabled = true
            dimView.removeFromSuperview()
            loadingView.removeFromSuperview()
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接