How to make simple search box in iOS

Issue #227

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
final class SearchBox: UIView {
lazy var textField: UITextField = {
let textField = UITextField()
let imageView = UIImageView(image: R.image.search()!)
imageView.frame.size = CGSize(width: 20 + 8, height: 20)
imageView.contentMode = .scaleAspectFit
textField.leftView = imageView
textField.leftViewMode = .always

return textField
}()

lazy var filterButton: UIButton = {
let button = UIButton(type: .custom)
button.setImage(R.image.filter()!, for: .normal)
button.imageEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)

return button
}()

lazy var backView: UIView = {
let view = UIView()
view.backgroundColor = .white
view.layer.cornerRadius = 10
view.layer.borderColor = R.color.lightGray.cgColor
view.layer.borderWidth = 0.5
view.layer.shadowOffset = CGSize(width: 1, height: 1)
view.layer.shadowOpacity = 0.8
view.layer.shadowColor = R.color.lightGray.cgColor

return view
}()

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

setup()
}

required init?(coder aDecoder: NSCoder) {
fatalError()
}

private func setup() {
addSubviews([backView, textField, filterButton])

NSLayoutConstraint.on([
filterButton.rightAnchor.constraint(equalTo: rightAnchor, constant: -8),
filterButton.centerYAnchor.constraint(equalTo: centerYAnchor),
filterButton.heightAnchor.constraint(equalToConstant: 44),
filterButton.widthAnchor.constraint(equalToConstant: 44),

textField.centerYAnchor.constraint(equalTo: centerYAnchor),
textField.leftAnchor.constraint(equalTo: leftAnchor, constant: 16),
textField.rightAnchor.constraint(equalTo: filterButton.leftAnchor, constant: -8)
])

NSLayoutConstraint.on([
backView.pinEdges(view: self, inset: UIEdgeInsets(top: 4, left: 4, bottom: -4, right: -4))
])
}
}

To apply padding to leftView, increase width and use contentMode

1
2
imageView.frame.size = CGSize(width: 20 + 8, height: 20)
imageView.contentMode = .scaleAspectFit

To make image in button smaller, use imageEdgeInsets with all positive values
To have round and shadow, specify shadowOpacity, cornerRadius, shadowOffset

searchbox

Comments