简体   繁体   中英

bad_Access exception when typing in UITextView

I don't know what is wrong with this code; when i start typing in the UITextView, the program terminates with exc_Bad_Access exception.

UIView *toolbar = [[UIView alloc] initWithFrame:CGRectMake(0, 430, 320, 44)];
toolbar.backgroundColor = [UIColor lightGrayColor];
UITextView *sendTextView = [[UITextView alloc] initWithFrame:CGRectMake(10, 9, 240, 26)];
sendTextView.backgroundColor = [UIColor whiteColor];
sendTextView.inputAccessoryView = toolbar;
sendTextView.layer.cornerRadius = 12.0;
[toolbar addSubview:sendTextView];
[self.view addSubview:toolbar];

The above code is inside the viewDidLoad method of a UIViewController which has a UIScrollView as its view.

Putting an editable text view in a toolbar seems strange. (What do you do when the user wants to edit it? Move it up above the keybaord? I wouldn't expect a toolbar to move OR to contain an editable field.) Nevertheless, I'd be surprised if doing that caused EXC_BAD_ACCESS.

Your problem is more likely in code that actually runs when you're typing, such as one of the text view delegate methods. If you can't find anything there, please post the stack trace at the time of the crash and code for the method that was actually running at the time.

Update: After you pointed it out in your comment, I see that you're setting the toolbar as the input accessory view for sendTextView and adding it to the view controller's view. I'd guess that what's happening here is that when you start editing the text view, the text view adds the toolbar to the keyboard's view without first removing it from the view controller's view. A given view can only be part of one view hierarchy at a time; adding it to your view and using it as the input accessory view won't work. If you look at Apple's sample code for using an accessory view you'll find that the view used as the accessory isn't part of the normal view hierarchy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM