Last active
August 28, 2019 22:48
-
-
Save hannesoid/ed78904e33a362889d2bd38f2f09ec3b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// EurekaWhitespaceWorkaround.swift | |
// | |
// Created by Hannes Oud on 23.11.16. | |
// Use this however you want. | |
import Eureka | |
/// Configures right-aligned text rows to make spaces visible on edit, | |
/// by temporary replacing them with non-breaking spaces. Call `EurekaWhitespaceWorkaround.configureTextCells()`. | |
/// - Note: this will set the `TextRow.defaultCellSetup` | |
final class EurekaWhitespaceWorkaround { | |
static func configureTextCells() { | |
let workaround = EurekaWhitespaceWorkaround() | |
TextRow.defaultCellSetup = { cell, row in | |
// the workaround object is retained here on purpose | |
workaround.configureWhiteSpaceWorkaround(forTextCell: cell) | |
} | |
} | |
private func configureWhiteSpaceWorkaround(forTextCell cell: TextCell) { | |
cell.textField.addTarget(self, action: #selector(EurekaWhitespaceWorkaround.replaceNormalSpacesWithNonBreakingSpaces(textField:)), for: .editingChanged) | |
cell.textField.addTarget(self, action: #selector(EurekaWhitespaceWorkaround.replaceNonBreakingSpacesWithNormalSpaces(textField:)), for: .editingDidEnd) | |
} | |
private dynamic func replaceNormalSpacesWithNonBreakingSpaces(textField: UITextField) { | |
textField.text = textField.text?.replacingOccurrences(of: " ", with: "\u{00a0}") | |
} | |
private dynamic func replaceNonBreakingSpacesWithNormalSpaces(textField: UITextField) { | |
textField.text = textField.text?.replacingOccurrences(of: "\u{00a0}", with: " ") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a good solution, but the cursor jumps to the end if you add a space in the middle of the string. This will put the cursor back (Swift 4):
@objc private dynamic func replaceNormalSpacesWithNonBreakingSpaces(textField: UITextField) {
let cursor = textField.selectedTextRange
textField.text = textField.text?.replacingOccurrences(of: " ", with: "\u{00a0}")
textField.selectedTextRange = cursor
}