快速突出显示文本时如何触发事件

时间:2019-05-13 21:25:05

标签: ios swift uitextfield

我想制作一个图书应用,用户可以在其中阅读其中的章节。我想添加一个功能,用户可以在其中突出显示文本并将其保留在应用程序中以备将来参考。快速选择文本后如何触发事件(例如带有突出显示图标的按钮)?请帮助

我已经用Google搜索了好几个小时了

//
//  ViewController.swift
//  platesofned
//
//  Created by Mauricio Kiyama on 5/13/19.
//  Copyright © 2019 Mauricio Kiyama. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    let myTextView: UITextField = {
        let label = UITextField()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.text = "Hello World"
        label.isSelected = true
        label.textColor = .black
        return label
    }()


    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(myTextView)
        myTextView.widthAnchor.constraint(equalToConstant: 100).isActive = true
        myTextView.heightAnchor.constraint(equalToConstant: 100).isActive = true
        myTextView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        myTextView.topAnchor.constraint(equalTo: view.topAnchor, constant: 100).isActive = true

        if let textRange = myTextView.selectedTextRange {

            let selectedText = myTextView.text(in: textRange)

            print(selectedText)
        }
    }


}

我想要一个在选择任何文本后都有按钮的框。

1 个答案:

答案 0 :(得分:0)

假设您要询问如何在UITextField中的选择更改时获取事件,则需要向UITextField的“ selectedTextRange”属性中添加观察者(来自UITextInput协议)。 / p>

这是一个小的示例视图控制器,它监听文本字段的此类事件:

class MyVC: UIViewController {
    var textField: UITextField!

    @objc override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "selectedTextRange" {
            if let tf = object as? UITextField {
                // This is our event and text field
                if let range = tf.selectedTextRange {
                    print("Updated selection = \(range)")
                }

                return
            }
        }

        // This isn't the event or the object we care about, pass it on
        super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .yellow

        textField = UITextField(frame: CGRect(x: 0, y: 0, width: 300, height: 44))
        textField.text = "Hello there. How are you?"

        // Options is empty because we don't care about the old range and we can get the new range from the text field
        textField.addObserver(self, forKeyPath: "selectedTextRange", options: [], context: nil)

        view.addSubview(textField)
    }

    deinit {
        textField.removeObserver(self, forKeyPath: "selectedTextRange")
    }
}