【问题标题】:How copy the result of two labels?如何复制两个标签的结果?
【发布时间】:2017-10-14 13:21:13
【问题描述】:

我有结果复制按钮的代码(来自 displayResultLabel

我怎样才能让它从两个标签一次复制(来自resultLabel,displayResultLabel

resultLabel - 历史记录

displayResultLabel - 结果


示例:

结果标签 - 5+22

显示结果标签 - 27

5+22=27

Photo


我试过这个,但我明白了: 可选 ("5 + 22") = 可选 ("27")

UIPasteboard.general.string = "\(String(describing: self.resultLabelText.text)) = \(String(describing: self.displayResultLabel.text))"

复制按钮

...
let deleteActions = UIAlertAction(title: NSLocalizedString("Copy history",comment: ""), style: .default, handler: {
        (alert: UIAlertAction!) -> Void in
        UIPasteboard.general.string = self.resultLabelText.text
        
        self.present(alert, animated: true, completion:nil)
    })
...

【问题讨论】:

    标签: ios swift string xcode calculator


    【解决方案1】:

    这是因为标签文本是可选的,这就是你得到的原因:

    Optional ("5 + 22") = Optional ("27")
    

    改为这样:

    if let resultText = resultLabelText.text, let displayText = displayResultLabel.text {
        UIPasteboard.general.string = "\(resultText) = \(displayText)"
    
    }
    

    【讨论】:

    • 非常感谢
    【解决方案2】:

    您只需解开您的值,因为 self.resultLabelText.textself.displayResultLabel.text 是可选的,这意味着返回的值可以是 nil 或有值。

    如果你确定你有一个值并且它可以被转换,只需通过放置一个感叹号来解开它们:self.resultLabelText.text!和self.displayResultLabel.text! 或按照 Rashwan 的建议使用 可选绑定。这是最安全的方式!

    Apple 文档的基础知识:Basics

    【讨论】:

    • 尽可能不要强制解包值。
    • 这就是我提到可选绑定的原因;)
    猜你喜欢
    • 2022-01-11
    • 2014-03-17
    • 2015-08-16
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    相关资源
    最近更新 更多