简体   繁体   中英

How to keep the text of a UILabel inside the safeArea?

I've created a custom UILabel in order to be able to change its safe area so the text could have some padding and look nicer, but after I changed my safeArea the text still go all the way from edge to edge and no padding added here's my code

class customLabel: UILabel {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setUp()

    }

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



    override var safeAreaInsets: UIEdgeInsets {
        return UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    }


    func setUp(){
        lineBreakMode = NSLineBreakMode.byWordWrapping
        numberOfLines = 0
        textColor = UIColor.white
        textAlignment = .center
        layer.cornerRadius = 8
        clipsToBounds = true
        backgroundColor = UIColor.black.withAlphaComponent(0.7)
        font = UIFont.boldSystemFont(ofSize: 20)
        translatesAutoresizingMaskIntoConstraints = false

    }

}

how to keep the text inside the new safeAreaInset?

thank you!

safeAreaInsets shouldn't be used for text padding. Safe Area was added to prevent covering UIView 's content by navigation bars, tab bars, toolbars etc. So you can override this variable in UIView subclasses to make it's subviews visible when you add constraints to UIView 's Safe Area. But since text in UILabel doesn't have constraints to Safe Area so overriding this variable doesn't make any sense.

Instead you need to override textRect(forBounds:limitedToNumberOfLines:) method of UILabel .

override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
    return bounds.insetBy(dx: 10, dy: 10)
}

insetBy(dx:dy:) method returns the rectangle with left and right insets from dx and top and bottom insets from dy .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM