在iOS中為UIView添加陰影還是比較簡(jiǎn)單的,只需要設(shè)置layer
的shadow
屬性就可以了,但是問(wèn)題在于設(shè)置陰影之后,必須設(shè)置masksToBounds
為NO
,而圓角圖片則要求masksToBounds
必須為YES
,兩者相互沖突,會(huì)導(dǎo)致無(wú)法正確的添加陰影。
正確的做法是先創(chuàng)建一個(gè)透明的UIView
,并添加陰影,設(shè)置masksToBounds
為NO
;
然后在透明的UIView
上添加圓角圖片,在subView
上設(shè)置masksToBounds
為YES
;
這樣,就可以完美實(shí)現(xiàn)對(duì)應(yīng)的陰影了。
let baseView = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
// add the shadow to the base view
baseView.backgroundColor = UIColor.clear
baseView.layer.shadowColor = UIColor.black.cgColor
baseView.layer.shadowOffset = CGSize(width: 3, height: 3)
baseView.layer.shadowOpacity = 0.7
baseView.layer.shadowRadius = 4.0
self.view.addSubview(baseView)
// add any other subcontent that you want clipped
let otherSubContent = UIImageView()
otherSubContent.image = UIImage(named: "lion")
otherSubContent.frame = baseView.bounds
otherSubContent.layer.masksToBounds = true
otherSubContent.layer.cornerRadius = 50
baseView.addSubview(otherSubContent)
效果如下圖:
屏幕快照 2017-08-03 下午2.53.46.png