Skip to content

Commit

Permalink
Fixes placeholder bug when it could go outside field bounds (#11)
Browse files Browse the repository at this point in the history
  • Loading branch information
Edgar Žigis authored Feb 10, 2022
1 parent c9231a4 commit 0087ad6
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
.DS_Store
.DS_Store
xcuserdata
17 changes: 14 additions & 3 deletions Sources/CocoaTextField/CocoaTextField.swift
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ public class CocoaTextField: UITextField {

private let padding: CGFloat = 16
private let hintFont = UIFont.systemFont(ofSize: 12)
private var initialBoundsWereCalculated = false

// MARK: Public

Expand Down Expand Up @@ -120,7 +121,6 @@ public class CocoaTextField: UITextField {
spellCheckingType = .no
layer.borderWidth = borderWidth
layer.cornerRadius = cornerRadius
hintLabel.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: frame.width, height: frame.height))
addSubview(hintLabel)
}

Expand All @@ -134,12 +134,12 @@ public class CocoaTextField: UITextField {
if isHintVisible {
// Small placeholder
self.hintLabel.alpha = 1
self.hintLabel.transform = CGAffineTransform.identity.translatedBy(x: self.padding, y: -self.hintHeight())
self.hintLabel.transform = CGAffineTransform.identity.translatedBy(x: 0, y: -self.hintHeight())
self.hintLabel.font = self.hintFont
} else if self.text?.isEmpty ?? true {
// Large placeholder
self.hintLabel.alpha = 1
self.hintLabel.transform = CGAffineTransform.identity.translatedBy(x: self.padding, y: 0)
self.hintLabel.transform = CGAffineTransform.identity.translatedBy(x: 0, y: 0)
self.hintLabel.font = self.font
} else {
// No placeholder
Expand Down Expand Up @@ -248,6 +248,17 @@ public class CocoaTextField: UITextField {
return CGSize(width: bounds.size.width, height: 64)
}

override open func layoutSubviews() {
super.layoutSubviews()
if !initialBoundsWereCalculated {
hintLabel.frame = CGRect(
origin: CGPoint(x: self.padding, y: 0),
size: CGSize(width: frame.width - self.padding * 3, height: frame.height)
)
initialBoundsWereCalculated = true
}
}

// MARK: Init

override init(frame: CGRect) {
Expand Down

0 comments on commit 0087ad6

Please sign in to comment.