使用 activityController 共享标签

using the activityController to share label

我有以下代码

 let textToShare = "Check out the test original for \(String(describing: bookTitle.text))"

        if let myWebsite = URL(string: "X") {//Enter link to your app here
            let objectsToShare = [textToShare, myWebsite] as [Any]
            let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)

            //Excluded Activities
            activityVC.excludedActivityTypes = [UIActivity.ActivityType.airDrop, UIActivity.ActivityType.addToReadingList]

            activityVC.popoverPresentationController?.sourceView = sender
            self.present(activityVC, animated: true, completion: nil)
        }

当我尝试共享标签文本 bookTitle.text 时,我得到输出 Optional("Test")。有没有办法使用 UIActivityViewController 共享 UILabel 文本?

I get the output Optional("Test")

实际上,您的方法是正确的。除了你需要 "unwrap" 那个可选的 属性 .text。您可以通过多种方式做到这一点。一种方法是强制解包(大多数时候不推荐!)像这样:

let textToShare = "Check out the test original for \(bookTitle.text!)"

或者另一种方法是使用 nil coalescing。像这样:

let textToShare = "Check out the test original for \(bookTitle.text ?? "")"

有关可选链接的更多信息 https://docs.swift.org/swift-book/LanguageGuide/OptionalChaining.html

P.S不需要使用String(describing:)。您通常在 print().

中使用它