jsdw_ios/QuickLocation/Core/Extension/UITextField+Extensions.swift

81 lines
2.9 KiB
Swift

//
// UITextField+Extensions.swift
// SHECommunity
//
// Created by psj on 2023/11/6.
//
import Foundation
import UIKit
extension UITextInput {
var isComposingText: Bool {
markedTextRange != nil
}
}
extension UITextField {
func placeholderColor(placeholder: String, color: UIColor, font: UIFont = UIFont.systemFont(ofSize:15) ) {
//
self.attributedPlaceholder = NSAttributedString.init(string:placeholder, attributes: [NSAttributedString.Key.font:font])
//
self.attributedPlaceholder = NSAttributedString.init(string:placeholder, attributes: [NSAttributedString.Key.foregroundColor:color])
}
/// EZSE: Add left padding to the text in textfield
public func addLeftTextPadding(_ blankSize: CGFloat) {
let leftView = UIView()
leftView.frame = CGRect(x: 0, y: 0, width: blankSize, height: frame.height)
self.leftView = leftView
self.leftViewMode = UITextField.ViewMode.always
}
@discardableResult
func limitCommittedText(to maximumLength: Int) -> String? {
guard !isComposingText else { return nil }
let currentText = text ?? ""
guard maximumLength > 0, currentText.count > maximumLength else {
return currentText
}
let cursorOffset = selectedTextRange.map {
offset(from: beginningOfDocument, to: $0.start)
} ?? (currentText as NSString).length
let limitedText = String(currentText.prefix(maximumLength))
text = limitedText
restoreCursor(to: cursorOffset, text: limitedText)
return limitedText
}
private func restoreCursor(to offset: Int, text: String) {
let validOffset = min(max(0, offset), (text as NSString).length)
guard let cursorPosition = position(from: beginningOfDocument, offset: validOffset) else { return }
selectedTextRange = textRange(from: cursorPosition, to: cursorPosition)
}
}
extension UITextView {
@discardableResult
func limitCommittedText(to maximumLength: Int) -> String? {
guard !isComposingText else { return nil }
let currentText = text ?? ""
guard maximumLength > 0, currentText.count > maximumLength else {
return currentText
}
let cursorOffset = selectedTextRange.map {
offset(from: beginningOfDocument, to: $0.start)
} ?? (currentText as NSString).length
let limitedText = String(currentText.prefix(maximumLength))
text = limitedText
restoreCursor(to: cursorOffset, text: limitedText)
return limitedText
}
private func restoreCursor(to offset: Int, text: String) {
let validOffset = min(max(0, offset), (text as NSString).length)
guard let cursorPosition = position(from: beginningOfDocument, offset: validOffset) else { return }
selectedTextRange = textRange(from: cursorPosition, to: cursorPosition)
}
}