Как создать UILabel с авторазмером, закругленными углами и тенью - PullRequest
0 голосов
/ 22 мая 2019

Попытка получить UILabel, которая удовлетворяет следующим трем требованиям:

  • автоматически изменяет размер в соответствии с его текстовым содержимым
  • имеет закругленные углы
  • имеет тень

Я могу выполнить два из трех требований - но, к сожалению, никогда не все три!

Я попробовал lbl4.layer.masksToBounds = true, и я получаю закругленные углы с выполненным авторазмером (но нетень) - см. изображение-1 ниже ...

Я попытался lbl4.layer.masksToBounds = false и получаю тень с автоматическим изменением размера (но не закругленными углами) - см. изображение-2 ниже ...

Что мне нужно сделать, чтобы получить все три требования ?????

Вот мой код:

let label_4: PaddingLabel = {

    let lbl4 = PaddingLabel(padding: UIEdgeInsets(top: 16.0, left: 16.0, bottom: 16.0, right: 16.0))
    lbl4.translatesAutoresizingMaskIntoConstraints = false
    lbl4.text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."


    lbl4.numberOfLines = 0
    lbl4.font = UIFont.systemFont(ofSize: 24.0)
    lbl4.textColor = .white
    lbl4.textAlignment = .center
    lbl4.textAlignment = .justified
    lbl4.backgroundColor = .blue
    lbl4.layer.cornerRadius = 15.0
    lbl4.clipsToBounds = false
    lbl4.layer.masksToBounds = true   // !!!!!!! OR false

    lbl4.layer.shadowColor = UIColor.black.cgColor
    lbl4.layer.shadowRadius = 15
    lbl4.layer.shadowOpacity = 0.9
    lbl4.layer.shadowOffset = .init(width: 7.0, height: 10.0)
    lbl4.layer.shouldRasterize = true
    return lbl4
}()

с lbl4.layer.masksToBounds = true

enter image description here

с lbl4.layer.masksToBounds = false

enter image description here

Здесьостальная часть привязки label_4 (по причинам полноты ...):

label_4.topAnchor.constraint(equalTo: label_3.bottomAnchor, constant: 50).isActive = true
label_4.leftAnchor.constraint(equalTo: contentView.safeAreaLayoutGuide.leftAnchor, constant: 20).isActive = true
label_4.rightAnchor.constraint(equalTo: contentView.safeAreaLayoutGuide.rightAnchor, constant: -20).isActive = true

Здесь класс PaddingLabel:

class PaddingLabel: UILabel {

    var padding: UIEdgeInsets?

    init(padding: UIEdgeInsets) {
        self.padding = padding
        super.init(frame: .zero)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func drawText(in rect: CGRect) {
        if let insets = padding {
            super.drawText(in: rect.inset(by: insets))
        }
    }

    override open var intrinsicContentSize: CGSize {
        guard let text = self.text else { return super.intrinsicContentSize }

        var contentSize = super.intrinsicContentSize
        var textWidth: CGFloat = frame.size.width
        var insetsHeight: CGFloat = 0.0
        var insetsWidth: CGFloat = 0.0

        if let insets = padding {
            insetsWidth += insets.left + insets.right
            insetsHeight += insets.top + insets.bottom
            textWidth -= insetsWidth
        }

        let newSize = text.boundingRect(with: CGSize(width: textWidth, height: CGFloat.greatestFiniteMagnitude),
                                        options: NSStringDrawingOptions.usesLineFragmentOrigin,
                                        attributes: [NSAttributedString.Key.font: (self.font ?? UIFont.systemFont(ofSize: self.font.pointSize))], context: nil)

        contentSize.height = ceil(newSize.size.height) + insetsHeight
        contentSize.width = ceil(newSize.size.width) + insetsWidth

        return contentSize
    }
}
...