问题
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 = UIAlertViewStylePlainTextInput;
But this isn't what i want. I want a bigger text input so a user can write a comment after a news for example.
Is this possible ?
回答1:
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.
回答2:
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:{})
}
来源:https://stackoverflow.com/questions/28454595/ios-uialertview-with-uitextview-editable