Свифт
![enter image description here](https://i.stack.imgur.com/P0nYc.png)
// corner radius
blueView.layer.cornerRadius = 10
// border
blueView.layer.borderWidth = 1.0
blueView.layer.borderColor = UIColor.black.cgColor
// shadow
blueView.layer.shadowColor = UIColor.black.cgColor
blueView.layer.shadowOffset = CGSize(width: 3, height: 3)
blueView.layer.shadowOpacity = 0.7
blueView.layer.shadowRadius = 4.0
Изучение возможностей
![enter image description here](https://i.stack.imgur.com/iYhPm.png)
![enter image description here](https://i.stack.imgur.com/VWHzr.png)
![enter image description here](https://i.stack.imgur.com/OLeZM.png)
![enter image description here](https://i.stack.imgur.com/YfhSC.png)
![enter image description here](https://i.stack.imgur.com/ozDVu.png)
Проблема 1: Тень обрезается
Что, если есть подслои или подпредставления (например, изображение), содержимое которых мы хотим обрезать до границ нашего представления?
![enter image description here](https://i.stack.imgur.com/pTiEu.png)
Мы можем сделать это с помощью
blueView.layer.masksToBounds = true
(В качестве альтернативы blueView.clipsToBounds = true
дает тот же результат .)
![enter image description here](https://i.stack.imgur.com/zRRBG.png)
Но, о нет! Тень также была обрезана, потому что она находится за пределами границ!Что делать?Что делать?
Решение
Использование отдельных видов для тени и границы.Базовый вид прозрачен и имеет тень.Граница просмотра обрезает любой другой субконтент, который у него есть, к своим границам.
// 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
// add the border to subview
let borderView = UIView()
borderView.frame = baseView.bounds
borderView.layer.cornerRadius = 10
borderView.layer.borderColor = UIColor.black.cgColor
borderView.layer.borderWidth = 1.0
borderView.layer.masksToBounds = true
baseView.addSubview(borderView)
// add any other subcontent that you want clipped
let otherSubContent = UIImageView()
otherSubContent.image = UIImage(named: "lion")
otherSubContent.frame = borderView.bounds
borderView.addSubview(otherSubContent)
Это дает следующий результат:
![enter image description here](https://i.stack.imgur.com/9PekY.png)
Проблема 2: Низкая производительность
Добавление закругленных углов и теней может привести к снижению производительности.Вы можете улучшить производительность, используя предопределенный путь для тени, а также указав, что он должен быть растеризован.Следующий код можно добавить в приведенный выше пример.
baseView.layer.shadowPath = UIBezierPath(roundedRect: baseView.bounds, cornerRadius: 10).cgPath
baseView.layer.shouldRasterize = true
baseView.layer.rasterizationScale = UIScreen.main.scale
См. этот пост для получения более подробной информации.См. здесь и здесь также.
Этот ответ был проверен с Swift 4 и Xcode 9.