Skip to content

Instantly share code, notes, and snippets.

@hannesoid
Last active August 28, 2019 22:48
Show Gist options
  • Save hannesoid/ed78904e33a362889d2bd38f2f09ec3b to your computer and use it in GitHub Desktop.
Save hannesoid/ed78904e33a362889d2bd38f2f09ec3b to your computer and use it in GitHub Desktop.
//
// 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: " ")
}
}
@kobble-git
Copy link

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
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment