Last active
October 11, 2017 08:32
-
-
Save nobuhito/b35390fe71b4b6e0fd758d3c8d9a894a to your computer and use it in GitHub Desktop.
TextViewにカーソルを前後や行頭行末に移動させるToolbarを追加
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
class ViewController: UIViewController { | |
@IBOutlet weak var TextView: UITextView! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do any additional setup after loading the view, typically from a nib. | |
let toolbar = UIToolbar() | |
let start = UIBarButtonItem(title: "|<", style: .plain, target: self, action: #selector(self.start)) | |
let back = UIBarButtonItem(title: "<", style: .plain, target: self, action: #selector(self.back)) | |
let forward = UIBarButtonItem(title: ">", style: .plain, target: self, action: #selector(self.forward)) | |
let end = UIBarButtonItem(title: ">|", style: .plain, target: self, action: #selector(self.end)) | |
toolbar.items = [start, back, forward, end] | |
toolbar.sizeToFit() | |
TextView.inputAccessoryView = toolbar | |
} | |
@objc func start() { | |
let cp = TextView.selectedTextRange! | |
if cp.start == TextView.beginningOfDocument { | |
return | |
} | |
let text = TextView.text! as NSString | |
let lineRange = text.lineRange(for: NSMakeRange(TextView.selectedRange.location, 0)) | |
let rangeStart = TextView.position(from: TextView.beginningOfDocument, offset: lineRange.location)! | |
TextView.selectedTextRange = TextView.textRange(from: rangeStart, to: rangeStart) | |
} | |
@objc func back() { | |
let cp = TextView.selectedTextRange! | |
if cp.start == TextView.beginningOfDocument { | |
return | |
} | |
let position = TextView.position(from: cp.start, offset: -1) | |
TextView.selectedTextRange = TextView.textRange(from: position!, to: position!) | |
} | |
@objc func end() { | |
let cp = TextView.selectedTextRange! | |
if cp.end == TextView.endOfDocument { | |
return | |
} | |
let text = "\(TextView.text!)\n" as NSString | |
let linerange = text.lineRange(for: NSMakeRange(TextView.selectedRange.location, 0)) | |
let rangeStart = TextView.position(from: TextView.beginningOfDocument, offset: linerange.location)! | |
let rangeEnd = TextView.position(from: rangeStart, offset: linerange.length - 1)! | |
TextView.selectedTextRange = TextView.textRange(from: rangeEnd, to: rangeEnd) | |
} | |
@objc func forward() { | |
let cp = TextView.selectedTextRange! | |
if cp.end == TextView.endOfDocument { | |
return | |
} | |
let position = TextView.position(from: cp.start, offset: 1) | |
TextView.selectedTextRange = TextView.textRange(from: position!, to: position!) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment