How to use UITextView in UIAlertController

后端 未结 6 1369
悲哀的现实
悲哀的现实 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条回答
  •  半阙折子戏
    2020-12-16 19:05

    Johno2110's solution worked best for me with a little cleanup and tweaking. Posting the code and a screenshot of the result here in case it helps anybody else out.

    Confirmed working with Swift 5.

    let textView = UITextView(frame: CGRect.zero)
    
    @IBAction func sendFeedback(_ sender: Any) {
        let alertController = UIAlertController(title: "Feedback \n\n\n\n\n", message: nil, preferredStyle: .alert)
    
        let cancelAction = UIAlertAction.init(title: "Cancel", style: .default) { (action) in
            alertController.view.removeObserver(self, forKeyPath: "bounds")
        }
        alertController.addAction(cancelAction)
    
        let saveAction = UIAlertAction(title: "Submit", style: .default) { (action) in
            let enteredText = self.textView.text
            alertController.view.removeObserver(self, forKeyPath: "bounds")
        }
        alertController.addAction(saveAction)
    
        alertController.view.addObserver(self, forKeyPath: "bounds", options: NSKeyValueObservingOptions.new, context: nil)
        textView.backgroundColor = UIColor.white
        textView.textContainerInset = UIEdgeInsets.init(top: 8, left: 5, bottom: 8, right: 5)
        alertController.view.addSubview(self.textView)
    
        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
                let xPos = rect.origin.x + margin
                let yPos = rect.origin.y + 54
                let width = rect.width - 2 * margin
                let height: CGFloat = 90
    
                textView.frame = CGRect.init(x: xPos, y: yPos, width: width, height: height)
            }
        }
    }
    

提交回复
热议问题