简体   繁体   中英

UITextView is nil when attempting to set for popover

I have two View Controllers: SavePopOverVC and MainVC . I also have a nib file called SavePopOver . SavePopOver has three items, a UIButton , a UIImage and a UITextView . The image and text view have outlets to property fields in SavePopOverVC called captionImage and captionTextView respectively. The button has an outlet to an IBAction in SavePopOverVC .

In MainVC.m I have the following two lines in my class extension.

SavePopOverVC *spvc;
UIPopoverController *popover;

In my viewDidLoad of the same file I have the following lines relating to my popover.

spvc = [[SavePopOverVC alloc] initWithNibNamed:@"SavePopOver" bundle:nil];
popover = [[UIPopoverController alloc] initWithContentViewController:spvc];

In my function that displays my popover, also in MainVC.m , I have the following lines.

[popover setPopoverContentSize:CGSizeMake(600,200)];
[popover presentPopoverFromRect:_header.frame inView:self.view permittedArrowDirection:UIPopoverArrowDirectionAny animated:YES];
[((SavePopOverVC *)popover.contentViewController).captionTextView setText:@"Some text here"];

However, captionTextView is nil when I make the setText: call. The app doesn't crash but the text isn't set. After the popover is displayed and I click on the UIButton to save the string typed in captionTextView I get the string just fine. So, I know the two are ultimately linked correctly, but how can I set captionTextView from when I display the popover?

If it is worth noting, I'm developing solely for iPad with this one.

It is most likely nil because its view isn't loaded at the time you set the text. Unlike most other modern languages, in Objective-C calling a method on a nil object doesn't cause an exception, it just does nothing.

To solve this, you can create a custom NSString property in your SavePopOverVC , eg

@property (nonatomic, copy) NSString *caption;

Before you call presentPopoverFromRect: , assign a value to this property. Inside SavePopOverVC , override viewDidLoad and set the captionTextView.text = self.caption;

There might be people who disagree with me, but I don't recommend exposing UI controls as properties in a view controller. This behaviour is one of the reasons for that.

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