Resizing a UILabel to accommodate insets

后端 未结 8 1661
梦谈多话
梦谈多话 2020-11-27 11:03

I\'m building a screen to scan barcodes, and I need to put a translucent screen behind some UILabels to improve visibility against light backgrounds.

He

8条回答
  •  有刺的猬
    2020-11-27 11:25

    Here is an example of what I used for a simple 10 unit padding on the left and right of the label with rounded corners. Just set the label text to center it's self and make it's class IndentedLabel and the rest takes care of itself. To modify the padding just scale up or down rect.size.width += (x)

    class IndentedLabel: UILabel {
    
        var edgeInsets:UIEdgeInsets = UIEdgeInsetsZero
    
        override func textRectForBounds(bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
            var rect = super.textRectForBounds(UIEdgeInsetsInsetRect(bounds, edgeInsets), limitedToNumberOfLines: numberOfLines)
    
            rect.size.width  += 20;
    
            return rect
        }
    
        override func drawTextInRect(rect: CGRect) {
            self.clipsToBounds = true
            self.layer.cornerRadius = 3
            super.drawTextInRect(UIEdgeInsetsInsetRect(rect, edgeInsets))
        }
    }
    

提交回复
热议问题