如何使用UIButton

时间:2016-12-19 22:10:49

标签: ios swift xcode swift3 xcode8

我想为用户添加一种功能,当按下按钮时,用户可以将图像添加到TextView,并且像在Apple Notes应用程序中一样选择图像。我尝试了一些代码,但没有运气......

我希望它看起来像一个例子: Notes example

这就是我的ViewController:

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!)
    }

2 个答案:

答案 0 :(得分:0)

添加UITextViewDelegate

在viewDidLoad()

中添加textView.delegate = self

类PostViewController:UIViewController,UITextFieldDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate, UITextViewDelegate { }

答案 1 :(得分:0)

enter image description here 因此,为按钮创建操作。

        myTextView.backgroundColor = UIColor(patternImage: UIImage(named: "angular")!)

enter image description here

现在只需为UIImage显示提供正确的参数,并为按钮选择处理编写逻辑。祝你好运!

在您获得委托图片的情况下 info [UIImagePickerControllerOriginalImage] as!的UIImage 只需在我改变时更改背景颜色。