iOS UIAlertview with uitextview editable

前端 未结 2 1346
轮回少年
轮回少年 2021-01-27 06:26

I\'m searching for a way of putting an UITextView editable inside an UIAlertView.

I know how to put a simple textfield with :

alert.alertViewStyle = UIAl         


        
相关标签:
2条回答
  • 2021-01-27 07:09

    Add a custom view into the alert view.

    Change preferredStyle to .alert and .actionsheet as per the requirement.

    func showPopUpWithTextView() {
            let alertController = UIAlertController(title: "\n\n\n\n\n\n", message: nil, preferredStyle: .actionSheet)
    
            let margin:CGFloat = 8.0
            let rect = CGRect(x: margin, y: margin, width: alertController.view.bounds.size.width - margin * 4.0, height: 100.0)
            let textView = UITextView(frame: rect)
            textView.backgroundColor = .clear
    
            alertController.view.addSubview(textView)
    
            let submitAction = UIAlertAction(title: "Something", style: .default, handler: {(alert: UIAlertAction!) in print("Submit")
                print(textView.text)
            })
    
            let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {(alert: UIAlertAction!) in print("cancel")})
    
            alertController.addAction(submitAction)
            alertController.addAction(cancelAction)
    
            self.present(alertController, animated: true, completion:{})
        }
    

    0 讨论(0)
  • 2021-01-27 07:22

    Unfortunately what you are after isn't possible with a UIAlertView.

    Apple don't allow developers to modify the view hierarchy of a UIAlertView or subclass it. Check out the Apple Documentation for UIAlertView. Under the section marked Subclassing note you will find

    The UIAlertView class is intended to be used as-is and does not support subclassing. The view hierarchy for this class is private and must not be modified.

    Unfortunately though because UIAlertView still has the addSubview: method so it contradicts what Apple are actually telling us but the reason this is still here is because UIAlertView is a subclass of UIView which has this method. So what Apple have done is they have overridden this method so that it does absolutely nothing so when you call [myAlertView addSubview:myView]; will do nothing and no view will be added to the UIAlertView.

    So to get the behavior you are after you will need to implement a Custom AlertView (Check out Google search for Custom UIAlertView).

    Fortunately in iOS 8 Apple introduced a new class called UIAlertController that allows you to get the behavior that you are after and they have deprecated the UIAlertView class.

    0 讨论(0)
提交回复
热议问题