带有照片的UI文本视图以全屏打开它



我正在尝试制作一个类似于Notes应用程序的应用程序。我有一个UITextView显示NSAttributedString。我可以使用NSTextAttachment添加照片,一切正常。

现在,当用户点击照片时,我想显示一个新UIViewController它将全屏显示所需的照片。我如何实现这一点?笔记应用程序具有这种确切的行为。

这是我所做的 一旦我从didFinishPickingMediaWithInfo获得图像,我就会得到图像URL

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
picker.dismiss(animated: true)
//1 Make a NSAttachmentVariable
let attachment = NSTextAttachment()
guard let image = info[.editedImage] as? UIImage else {
print("No image found")
return
}
//2 get the ImageURL
guard let imageURL = info[.imageURL] as? URL else  {
print("No url")
return
}
//3 optional Resize the image
let resizedImage =  self.resizeImage(image: image, targetSize: CGSize(width: txtView.frame.size.width, height: 200))
//4 add the fetched image to the attachment created earlier to display on text view
attachment.image = resizedImage
//5 insert the attachment to the textview
let attString = NSMutableAttributedString(attachment: attachment)
txtView.textStorage.insert(attString, at: txtView.selectedRange.location)
//6 get the range of the whole image from the textview string
let range = NSString(string: attString.string).range(of: attString.string, options: String.CompareOptions.caseInsensitive)
//7 add the fetched image url we got earlier at //2 to the attachment 
attString.addAttribute(.link, value: imageURL, range: range)
//8 add the attributed text to the text view
txtView.attributedText = attString
}

现在使用 shouldInteractWith from textview 从 url 打开图像不要忘记将 UITextViewDelegate 作为扩展添加到您的控制器

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "Details") as! DetailsImage
let data = try? Data(contentsOf: URL)
if let imageData = data {
newViewController.image = UIImage(data: imageData)!
}
self.present(newViewController, animated: true, completion: nil)
//UIApplication.shared.open(URL)
return false
}

这用于从您的文本视图中打开 url,现在我们正在使用我们获得的 url,将其更改为数据并将另一个视图控制器的图像变量设置为返回的数据

这是另一个视图控制器


import UIKit
class DetailsImage: UIViewController{
var image = UIImage()
@IBOutlet weak var imgView: UIImageView!
override func viewDidLoad() {
imgView.image = image
}
}

重要提示:

点击不能非常简短,这意味着 iOS 会忽略快速点击。如果你觉得这很烦人,你可以考虑这样的事情:https://gist.github.com/benjaminbojko/c92ac19fe4db3302bd28。

就是这样,您可以在新打开的VC上设置导航按钮以返回文本视图的vc

最新更新