gpt4 book ai didi

ios - 如何在 swift 中突出显示文本时触发事件

转载 作者:行者123 更新时间:2023-11-29 05:46:22 26 4
gpt4 key购买 nike

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

我在谷歌上搜索了几个小时,但一无所获

//
// 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)
}
}


}

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

最佳答案

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

这是一个小的 View Controller 示例,用于监听文本字段的此类事件:

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")
}
}

关于ios - 如何在 swift 中突出显示文本时触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56120059/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com