-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create
UITextField
extension for set a selected range via `Range<St…
…ring.Index>`
- Loading branch information
Showing
2 changed files
with
45 additions
and
0 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
// | ||
// UITextFieldExtension.swift | ||
// FormattedTextField | ||
// | ||
// Created by Evgeniy Yurtaev on 25/10/2016. | ||
// Copyright © 2016 Evgeniy Yurtaev. All rights reserved. | ||
// | ||
|
||
import UIKit | ||
|
||
extension UITextField { | ||
var selectedCharachtersRange: Range<String.Index>? { | ||
get { | ||
guard let selectedTextRange = selectedTextRange else { | ||
return nil | ||
} | ||
guard let text = text else { | ||
return nil | ||
} | ||
let location = offset(from: beginningOfDocument, to: selectedTextRange.start) | ||
let length = offset(from: selectedTextRange.start, to: selectedTextRange.end) | ||
let range = text.range(fromUtf16NsRange: NSMakeRange(location, length)) | ||
|
||
return range | ||
} | ||
set(value) { | ||
guard let value = value else { | ||
selectedTextRange = nil | ||
return | ||
} | ||
guard let text = text else { | ||
return | ||
} | ||
let utf16Range = text.utf16Nsrange(fromRange: value) | ||
|
||
let from = position(from: beginningOfDocument, offset: utf16Range.location)! | ||
let to = position(from: from, offset: utf16Range.length)! | ||
selectedTextRange = textRange(from: from, to: to) | ||
} | ||
} | ||
} |