美文网首页
如何设置SuperView背景透明的时候,子视图不透明

如何设置SuperView背景透明的时候,子视图不透明

作者: TomatosX | 来源:发表于2016-03-05 02:06 被阅读252次

1、创建视图

首先我们先创建一个背景的View,作为父类的View,取名为backgroundView,然后我们创建一个子View,取名为childView,然后将childView放在backgroundView上面。
并且我们设置backgroundView的透明度alpha参数的值为0.3。

具体代码如下:

let backgroundView = UIView(frame: CGRectMake(100, 100, 200, 200))
backgroundView.backgroundColor = UIColor.orangeColor()
let childView = UIView(frame: CGRectMake(20, 20, 100, 100))
childView.backgroundColor = UIColor.purpleColor()

backgroundView.alpha = 0.3

backgroundView.addSubview(childView)
self.view.addSubview(backgroundView)
同时透明

运行程序,我们发现,子视图childView的透明度也被设置成为0.3。如果想让backgroundView透明,但是childView不透明该怎么做呢?

2、只将backgroundView透明度设置为0.3

这时,我们需要用到一个UIColor类中的一个方法
- colorWithAlphaComponent:

所填写的参数就是你要设置的透明度,代码修改如下:

let backgroundView = UIView(frame: CGRectMake(100, 100, 200, 200))
backgroundView.backgroundColor = UIColor.orangeColor().colorWithAlphaComponent(0.3)
let childView = UIView(frame: CGRectMake(20, 20, 100, 100))
childView.backgroundColor = UIColor.purpleColor()

// backgroundView.alpha = 0.3

backgroundView.addSubview(childView)
self.view.addSubview(backgroundView)
父视图透明

运行程序,就会惊奇的发现子视图的透明度仍然为1。

相关文章

网友评论

      本文标题:如何设置SuperView背景透明的时候,子视图不透明

      本文链接:https://www.haomeiwen.com/subject/rbgokttx.html