How to use UITextView in UIAlertController

后端 未结 6 1360
悲哀的现实
悲哀的现实 2020-12-16 18:48

I created a popup alert using alert controller and added two alert actions(ok and cancel) as below.

UIAlertController * alert=   [UIAlertController
                  


        
6条回答
  •  萌比男神i
    2020-12-16 18:58

    Fantastic solutions above. Some needed some manipulation to work for Swift 4.2, here is the conversion for that. I've also added some padding in the TextView to make it athletically more pleasing.

    let textView = UITextView(frame: CGRect.zero)
    
    @IBAction func alert(_ sender: Any) {
    
        let alertController = UIAlertController(title: "\n\n\n\n\n", message: nil, preferredStyle: .alert)
    
        textView.textContainerInset = UIEdgeInsets.init(top: 8, left: 5, bottom: 8, right: 5)
    
        let saveAction = UIAlertAction(title: "OK", style: .default) { (action) in
            self.label.text = self.textView.text
            alertController.view.removeObserver(self, forKeyPath: "bounds")
        }
    
        saveAction.isEnabled = false
    
        let cancelAction = UIAlertAction.init(title: "Cancel", style: .default) { (action) in
            alertController.view.removeObserver(self, forKeyPath: "bounds")
        }
    
        alertController.view.addObserver(self, forKeyPath: "bounds", options: NSKeyValueObservingOptions.new, context: nil)
    
        NotificationCenter.default.addObserver(forName: UITextView.textDidChangeNotification, object: textView, queue: OperationQueue.main) { (notification) in
            saveAction.isEnabled = self.textView.text != ""
        }
    
        textView.backgroundColor = UIColor.white
        alertController.view.addSubview(self.textView)
    
        alertController.addAction(saveAction)
        alertController.addAction(cancelAction)
    
        self.present(alertController, animated: true, completion: nil)
    
    
    }
    
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "bounds"{
            if let rect = (change?[NSKeyValueChangeKey.newKey] as? NSValue)?.cgRectValue {
                let margin:CGFloat = 8.0
                textView.frame = CGRect.init(x: rect.origin.x + margin, y: rect.origin.y + margin, width: rect.width - 2*margin, height: rect.height / 2)
                textView.bounds = CGRect.init(x: rect.origin.x + margin, y: rect.origin.y + margin, width: rect.width - 2*margin, height: rect.height / 2)
            }
        }
    }
    

提交回复
热议问题