-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFilterBar.swift
89 lines (74 loc) · 2.78 KB
/
FilterBar.swift
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
//
// FilterBar.swift
// whereim
//
// Created by Buganini Q on 21/05/2017.
// Copyright © 2017 Where.IM. All rights reserved.
//
import UIKit
protocol FilterBarDelegate {
func onFilter(keyword: String?)
}
class FilterBar: UIStackView {
let background = UIView()
let keyword = UITextField()
let btn_clear = UIButton()
var delegate: FilterBarDelegate?
init() {
super.init(frame: .zero)
setView()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setView()
}
func setView() {
self.translatesAutoresizingMaskIntoConstraints = false
self.axis = .horizontal
self.alignment = .leading
self.distribution = .fill
self.layoutMargins = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
self.isLayoutMarginsRelativeArrangement = true
background.translatesAutoresizingMaskIntoConstraints = false
background.backgroundColor = .gray
self.insertSubview(background, at: 0)
background.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
background.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
background.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
background.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
keyword.translatesAutoresizingMaskIntoConstraints = false
keyword.backgroundColor = .white
keyword.layer.cornerRadius = 10
keyword.addTarget(self, action: #selector(keyword_changed(sender:)), for: .editingChanged)
self.addArrangedSubview(keyword)
btn_clear.translatesAutoresizingMaskIntoConstraints = false
btn_clear.contentEdgeInsets = UIEdgeInsetsMake(5, 10, 5, 5)
btn_clear.setTitle("✘", for: .normal)
btn_clear.isHidden = true
btn_clear.addTarget(self, action: #selector(clear_clicked(sender:)), for: .touchUpInside)
self.addArrangedSubview(btn_clear)
keyword.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
btn_clear.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
}
@objc func keyword_changed(sender: Any) {
if keyword.text != nil && !keyword.text!.isEmpty {
if let d = delegate {
d.onFilter(keyword: keyword.text)
}
btn_clear.isHidden = false
} else {
if let d = delegate {
d.onFilter(keyword: nil)
}
btn_clear.isHidden = true
}
}
@objc func clear_clicked(sender: Any) {
btn_clear.isHidden = true
keyword.text = ""
keyword.resignFirstResponder()
if let d = delegate {
d.onFilter(keyword: nil)
}
}
}