-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnderlineSegmentedControl.swift
More file actions
98 lines (84 loc) · 3.04 KB
/
UnderlineSegmentedControl.swift
File metadata and controls
98 lines (84 loc) · 3.04 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
//
// UnderlineSegmentedControl.swift
//
// Created by Massimiliano DI MELLA on 29/08/2019.
// Copyright © 2019 MDM. All rights reserved.
//
import UIKit
class UnderlineSegmentedControl: UIControl {
var buttons = [UIButton]()
var selector: UIView!
var selectedSegmentIndex: Int = 0
@IBInspectable var buttonTitles: String = "" {
didSet {
updateView()
}
}
@IBInspectable var textColor : UIColor = .black {
didSet {
updateView()
}
}
@IBInspectable var selectedTextColor : UIColor = .blue {
didSet {
updateView()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
// fatalError("non implementata")
}
func updateView() {
buttons.removeAll()
subviews.forEach { v in
v.removeFromSuperview()
}
let titles = buttonTitles.components(separatedBy: ",")
for title in titles {
let button = UIButton(type: .system)
button.setTitle(title, for: .normal)
button.setTitleColor(textColor, for: .normal)
button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
buttons.append(button)
// colore alternativo
}
buttons[0].setTitleColor(selectedTextColor, for: .normal)
let selectorWidth = frame.width / CGFloat(titles.count)
let y = frame.maxY - frame.minY - 3.0
selector = UIView(frame: CGRect(x: 0, y: y, width: selectorWidth, height: 2))
selector.layer.cornerRadius = 16
selector.layer.masksToBounds = true
selector.backgroundColor = selectedTextColor
addSubview(selector)
let stackView = UIStackView.init(arrangedSubviews: buttons)
stackView.axis = .horizontal
stackView.alignment = .fill
stackView.distribution = .fillEqually
stackView.spacing = 0.0
addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
stackView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
stackView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
}
override func draw(_ rect: CGRect) {
}
@objc func buttonTapped(_ sender: UIButton) {
for (index, btn) in buttons.enumerated() {
btn.setTitleColor(textColor, for: .normal)
if btn == sender {
selectedSegmentIndex = index
let position = btn.center.x
UIView.animate(withDuration: 0.3) {
self.selector.center.x = position
}
btn.setTitleColor(selectedTextColor, for: .normal)
}
}
sendActions(for: .valueChanged)
}
}