英文:
Edit UITextField in UIKit so that the text can be edited via buttons
问题
我目前正在开发一个备忘录应用,其中我有一个UITextField。当您选择文本时,会出现一个弹出窗口,您可以在其中格式化文本(请参阅截图)。我希望通过按钮实现这个功能。
所以我有一个用户正在输入内容的UITextfield,然后我有一个按钮,比如粗体按钮,如果用户点击它,即使按钮启用,即将输入的文本也应该是粗体的。
我的问题是“旧”文本总是变粗。这是我的当前解决方案:
var isBoldEnabled = false
override func viewDidLoad() {
super.viewDidLoad()
// 为文本字段设置初始字体
textField.font = UIFont.systemFont(ofSize: 16)
}
@IBAction func boldButtonTapped(_ sender: Any) {
// 切换isBoldEnabled变量
isBoldEnabled = !isBoldEnabled
// 使用现有文本和当前字体创建新的带属性字符串
let attributedString = NSMutableAttributedString(string: textField.text ?? "")
let attributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: textField.font as Any]
attributedString.addAttributes(attributes, range: NSRange(location: 0, length: attributedString.length))
// 如果粗体按钮已启用,为所选文本添加粗体字体属性
if isBoldEnabled {
let boldAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: textField.font!.pointSize) as Any]
let selectedRange = textField.selectedTextRange
if selectedRange != nil {
let range = textField.selectedRange
attributedString.addAttributes(boldAttributes, range: NSRange(location: range.location, length: range.length))
}
}
// 将带属性文本设置为文本字段的文本
textField.attributedText = attributedString
}
有没有更好的方法可以仅通过更改即将输入的文本来启用此功能?感谢大家!
1: https://i.stack.imgur.com/4dfH3.png
<details>
<summary>英文:</summary>
I am currently developing a Notes app where I have a UITextField. When you select texts there is a popup where you can Format the text (see Screenshot). I want to have that functionality via buttons.
So I have a UITextfield where the user is typing something into and then I have e.g. a button which says bold and if the user clicks it the upcoming text should be bold as long as the button is enabled.
My issue is that the "old" text always goes bold. This is my current solution:
var isBoldEnabled = false
override func viewDidLoad() {
super.viewDidLoad()
// Set the initial font for the text field
textField.font = UIFont.systemFont(ofSize: 16)
}
@IBAction func boldButtonTapped(_ sender: Any) {
// Toggle the isBoldEnabled variable
isBoldEnabled = !isBoldEnabled
// Create a new attributed string with the existing text and the current font
let attributedString = NSMutableAttributedString(string: textField.text ?? "")
let attributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: textField.font as Any]
attributedString.addAttributes(attributes, range: NSRange(location: 0, length: attributedString.length))
// If the bold button is enabled, add the bold font attribute for the selected text
if isBoldEnabled {
let boldAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: textField.font!.pointSize) as Any]
let selectedRange = textField.selectedTextRange
if selectedRange != nil {
let range = textField.selectedRange
attributedString.addAttributes(boldAttributes, range: NSRange(location: range.location, length: range.length))
}
}
// Set the attributed text to the text field
textField.attributedText = attributedString
}
Has anyone a better approach how this functionality can be enabled with only changing the upcoming typing?
Thanks all![![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/4dfH3.png
</details>
# 答案1
**得分**: 2
根据您要做多少...
对于复杂、功能丰富的“富文本编辑”,我建议搜索已经构建好的解决方案 - 开源项目有很多。如果找不到完全符合您需求的解决方案,我相信您可以找到一个接近的解决方案,然后通过编辑代码来满足您的需求。
对于一个相对简单的实现,您可以设置文本字段的`.typingAttributes`属性 - 参见Apple的[文档][1]。
以下是一个非常简单的示例:
```swift
class ViewController: UIViewController {
let textField = UITextField()
let normalFont: UIFont = .systemFont(ofSize: 17, weight: .regular)
let boldFont: UIFont = .systemFont(ofSize: 17, weight: .bold)
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
textField.borderStyle = .roundedRect
textField.font = normalFont
let v = UILabel()
v.text = "加粗开/关"
let sw = UISwitch()
let ctrlStack = UIStackView(arrangedSubviews: [v, sw])
ctrlStack.spacing = 8
ctrlStack.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(ctrlStack)
textField.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(textField)
let g = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
ctrlStack.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0),
ctrlStack.centerXAnchor.constraint(equalTo: g.centerXAnchor),
textField.topAnchor.constraint(equalTo: ctrlStack.bottomAnchor, constant: 20.0),
textField.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 40.0),
textField.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -40.0),
])
sw.addTarget(self, action: #selector(swChanged(_:)), for: .valueChanged)
}
@objc func swChanged(_ sender: UISwitch) {
textField.typingAttributes?[NSAttributedString.Key.font] = sender.isOn ? boldFont : normalFont
}
}
看起来是这样的:
点击开关以打开粗体,然后输入一些文字:
关闭粗体,然后输入更多文字:
希望这有所帮助!
<details>
<summary>英文:</summary>
Depending on how much you want to do...
For complex, full-featured "rich-text editing" I'd suggest searching for already build solutions - lot's of open-source out there. If you can't find one to do exactly what you need, I'm sure you could find one close enough that you could go through the code and edit it to suit your needs.
For a fairly simple implementation, you can set the text field's `.typingAttributes` - see Apple's [1].
Here's a very quick example:
class ViewController: UIViewController {
let textField = UITextField()
let normalFont: UIFont = .systemFont(ofSize: 17, weight: .regular)
let boldFont: UIFont = .systemFont(ofSize: 17, weight: .bold)
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
textField.borderStyle = .roundedRect
textField.font = normalFont
let v = UILabel()
v.text = "Bold on/off"
let sw = UISwitch()
let ctrlStack = UIStackView(arrangedSubviews: [v, sw])
ctrlStack.spacing = 8
ctrlStack.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(ctrlStack)
textField.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(textField)
let g = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
ctrlStack.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0),
ctrlStack.centerXAnchor.constraint(equalTo: g.centerXAnchor),
textField.topAnchor.constraint(equalTo: ctrlStack.bottomAnchor, constant: 20.0),
textField.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 40.0),
textField.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -40.0),
])
sw.addTarget(self, action: #selector(swChanged(_:)), for: .valueChanged)
}
@objc func swChanged(_ sender: UISwitch) {
textField.typingAttributes?[NSAttributedString.Key.font] = sender.isOn ? boldFont : normalFont
}
}
Looks like this:
[![enter image description here][2]][2]
tap the switch to turn bold "On" and type a little more:
[![enter image description here][3]][3]
turn bold "Off" and type some more:
[![enter image description here][4]][4]
[1]: https://developer.apple.com/documentation/uikit/uitextfield/1619632-typingattributes
[2]: https://i.stack.imgur.com/vEiu7.png
[3]: https://i.stack.imgur.com/e8Y87.png
[4]: https://i.stack.imgur.com/6uKZF.png
</details>
# 答案2
**得分**: 0
当您尝试取消文本的“加粗”时,您将默认字体设置为属性字符串,作为文本字段的字体
```swift
UIFont.boldSystemFont(ofSize: textField.font!.pointSize) as Any
以前设置为加粗
所以,请将您的代码更改为:
var isBoldEnabled = false
let defaultFont = UIFont.systemFont(ofSize: 16)
override func viewDidLoad() {
super.viewDidLoad()
// 为文本字段设置初始字体
textField.font = defaultFont
}
@IBAction func boldButtonTapped(_ sender: Any) {
// 切换 isBoldEnabled 变量
isBoldEnabled = !isBoldEnabled
// 使用现有文本和当前字体创建新的属性字符串
let attributedString = NSMutableAttributedString(string: textField.text ?? "")
let attributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: defaultFont as Any]
attributedString.addAttributes(attributes, range: NSRange(location: 0, length: attributedString.length))
...
}
英文:
When you try to "unbold" your text, you're setting default font to attributed string as font from your textfield
UIFont.boldSystemFont(ofSize: textField.font!.pointSize) as Any
which was previously set as bold
So, change your code to
var isBoldEnabled = false
let defaultFont = UIFont.systemFont(ofSize: 16)
override func viewDidLoad() {
super.viewDidLoad()
// Set the initial font for the text field
textField.font = defaultFont
}
@IBAction func boldButtonTapped(_ sender: Any) {
// Toggle the isBoldEnabled variable
isBoldEnabled = !isBoldEnabled
// Create a new attributed string with the existing text and the current font
let attributedString = NSMutableAttributedString(string: textField.text ?? "")
let attributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: defaultFont as Any]
attributedString.addAttributes(attributes, range: NSRange(location: 0, length: attributedString.length))
...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论