PaddedUILabel.swift 1.63 KB
Newer Older
Zach Knox's avatar
Zach Knox committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//
//  PaddedUILabel.swift
//  WhatsOpen
//
//  Created by Zach Knox on 11/11/17.
//  Copyright © 2017 SRCT. All rights reserved.
//

import UIKit


// Based on this
// https://stackoverflow.com/questions/21167226/resizing-a-uilabel-to-accommodate-insets/21267507#21267507
// The entire reason for this subclass of UILabel is for the openClosedLabel in FacilityCollectionViewCell
class PaddedUILabel: UILabel {

    var textInsets = UIEdgeInsets.zero {
        didSet { invalidateIntrinsicContentSize() }
    }
    
    override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
Zach Knox's avatar
Zach Knox committed
22
        let insetRect = bounds.inset(by: textInsets)
Zach Knox's avatar
Zach Knox committed
23
24
25
26
27
        let textRect = super.textRect(forBounds: insetRect, limitedToNumberOfLines: numberOfLines)
        let invertedInsets = UIEdgeInsets(top: -textInsets.top,
                                          left: -textInsets.left,
                                          bottom: -textInsets.bottom,
                                          right: -textInsets.right)
Zach Knox's avatar
Zach Knox committed
28
        return textRect.inset(by: invertedInsets)
Zach Knox's avatar
Zach Knox committed
29
30
31
    }
    
    override func drawText(in rect: CGRect) {
Zach Knox's avatar
Zach Knox committed
32
        super.drawText(in: rect.inset(by: textInsets))
Zach Knox's avatar
Zach Knox committed
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
    }
    
}

@IBDesignable
extension PaddedUILabel {
    
    // currently UIEdgeInsets is no supported IBDesignable type,
    // so we have to fan it out here:
    @IBInspectable
    var leftTextInset: CGFloat {
        set { textInsets.left = newValue }
        get { return textInsets.left }
    }
    
    @IBInspectable
    var rightTextInset: CGFloat {
        set { textInsets.right = newValue }
        get { return textInsets.right }
    }
    
}