我想为用户添加一种功能,当按下按钮时,用户可以将图像添加到TextView,并且像在Apple Notes应用程序中一样选择图像。我尝试了一些代码,但没有运气......
这就是我的ViewController:
到目前为止的代码:
class PostViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet var titleTextField: UITextField!
@IBOutlet var contentTextField: UITextView!
@IBOutlet var bottomConstraint: NSLayoutConstraint!
let imagePicker = UIImagePickerController()
var selectedImage: UIImage!
@IBAction func chooseImageTapped(_ sender: UIButton) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary;
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
private func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : AnyObject])
{
self.selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
dismiss(animated:true, completion: nil)
let textView = contentTextField
let attributedString = NSMutableAttributedString(attributedString: (textView?.attributedText)!)
let textAttachment = NSTextAttachment()
textAttachment.image = self.selectedImage
let oldWidth = textAttachment.image!.size.width;
let scaleFactor = oldWidth / ((textView?.frame.size.width)! - 10);
textAttachment.image = UIImage(cgImage: textAttachment.image!.cgImage!, scale: scaleFactor, orientation: .up)
let attrStringWithImage = NSAttributedString(attachment: textAttachment)
attributedString.replaceCharacters(in: NSMakeRange(6, 1), with: attrStringWithImage)
textView?.attributedText = attributedString;
self.view.addSubview(textView!)
}
答案 0 :(得分:0)
添加UITextViewDelegate
在viewDidLoad()
中添加textView.delegate = self类PostViewController:UIViewController,UITextFieldDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate, UITextViewDelegate { }
答案 1 :(得分:0)