summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/CustomTextField.swift
blob: 9c400f4720a9a4033ffa84d0d70cefb4890d6a57 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//
//  CustomTextField.swift
//  MullvadVPN
//
//  Created by pronebird on 16/09/2020.
//  Copyright © 2020 Mullvad VPN AB. All rights reserved.
//

import Foundation
import UIKit

class CustomTextField: UITextField {

    var cornerRadius: CGFloat = UIMetrics.controlCornerRadius {
        didSet {
            layer.cornerRadius = cornerRadius
        }
    }

    var textMargins = UIMetrics.textFieldMargins {
        didSet {
            setNeedsLayout()
        }
    }

    var placeholderTextColor: UIColor = UIColor.TextField.placeholderTextColor {
        didSet {
            updatePlaceholderTextColor()
        }
    }

    override var placeholder: String? {
        didSet {
            updatePlaceholderTextColor()
        }
    }

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

        textColor = UIColor.TextField.textColor
        layer.cornerRadius = cornerRadius
        clipsToBounds = true
    }

    override func didAddSubview(_ subview: UIView) {
        super.didAddSubview(subview)

        // Internally `UITextField` adds the placeholder label to its view hierarchy.
        // Intercept it here and update the text color.
        if let placeholderLabel = subview as? UILabel {
            placeholderLabel.textColor = placeholderTextColor
        }
    }

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

    override func textRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.inset(by: textMargins)
    }

    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        return textRect(forBounds: bounds)
    }

    private func updatePlaceholderTextColor() {
        for case let placeholderLabel as UILabel in subviews {
            placeholderLabel.textColor = placeholderTextColor
            break
        }
    }
}