Resizing a UILabel to accommodate insets

后端 未结 8 1669
梦谈多话
梦谈多话 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:28

    Here is a Swift version of a UILabel subclass (same as @Nikolai's answer) that creates an additional padding around the text of a UILabel:

    class EdgeInsetLabel : UILabel {
        var edgeInsets:UIEdgeInsets = UIEdgeInsetsZero
    
        override func textRectForBounds(bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
            var rect = super.textRectForBounds(UIEdgeInsetsInsetRect(bounds, edgeInsets), limitedToNumberOfLines: numberOfLines)
    
            rect.origin.x -= edgeInsets.left
            rect.origin.y -= edgeInsets.top
            rect.size.width  += (edgeInsets.left + edgeInsets.right);
            rect.size.height += (edgeInsets.top + edgeInsets.bottom);
    
            return rect
        }
    
        override func drawTextInRect(rect: CGRect) {
            super.drawTextInRect(UIEdgeInsetsInsetRect(rect, edgeInsets))
        }
    }
    
    0 讨论(0)
  • 2020-11-27 11:28

    Swift 5 version of Nikolai Ruhe answer:

    extension UIEdgeInsets {
       func apply(_ rect: CGRect) -> CGRect {
          return rect.inset(by: self)
       }
    }
    
    class EdgeInsetLabel: UILabel {
      var textInsets = UIEdgeInsets.zero {
          didSet { invalidateIntrinsicContentSize() }
      }
    
      override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
        let insetRect = bounds.inset(by: textInsets)
        let textRect = super.textRect(forBounds: insetRect, limitedToNumberOfLines: numberOfLines)
        let invertedInsets = UIEdgeInsets(top: -textInsets.top,
                                          left: -textInsets.left,
                                          bottom: -textInsets.bottom,
                                          right: -textInsets.right)
        return textRect.inset(by: invertedInsets)
      }
    
      override func drawText(in rect: CGRect) {
          super.drawText(in: rect.inset(by: textInsets))
      }}
    
    0 讨论(0)
提交回复
热议问题