ios - 为什么这个委托(delegate)不适用于 UITextView
<p><pre><code>- (void)viewDidLoad
{
;
}
-(id)init{
self = ;
if (self) {
//self.view.delegate = self;
self.txtMain.userInteractionEnabled = YES;
self.txtMain.delegate = self;
}
return self;
}
-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
return ;
}
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
NSLog(@"textViewShouldBeginEditing:");
return YES;
}
</code></pre>
<p>self.txtMain 是我在 xib 中的 Root View :WritingView,而我的 ViewController 实现了协议(protocol) UITextViewDelegate,如下所示:</p>
<pre><code>@interface WritingViewController : UIViewController<UITextViewDelegate>
{
}
@property (strong, nonatomic) IBOutlet UITextView *txtMain;
</code></pre>
<p>我在 UITextViewDelegate 的 textViewShouldBeginEditing 或其他函数中设置了断点,但为什么从来没有进入?
顺便说一下,这个 ViewController 是由另一个 ViewController 创建的,像这样:</p>
<pre><code>WritingViewController *aViewController = [ initWithNibName:@"WritingView" bundle:nil];
;
;
</code></pre>
<p>谁能告诉我为什么它不起作用,然后我更改了初始化代码:</p>
<pre><code>-(id)init{
self = ;
if (self) {
UITextView *txtView = [ initWithFrame:self.view.frame];
txtView.textColor = ;
txtView.font = ;
txtView.text =@"Now is the time for all good developers tocome to serve their country.\n\nNow is the time for all good developers to cometo serve their country.";//
self.txtMain = txtView;
self.txtMain.userInteractionEnabled = YES;
self.txtMain.delegate = self;
;
}
return self;
}
</code></pre>
<p>显然我使用了一个空白 View 作为 Root View ,但是这一次,当我点击文本时,程序在 main() 中崩溃了:</p>
<pre><code> return UIApplicationMain(argc, argv, nil, NSStringFromClass());
</code></pre>
<p>在控制台中:</p>
<pre><code>2013-11-03 22:53:57.514 Wheel demo *** -: message sent to deallocated instance 0x9b4eeb0
</code></pre>
<p>(lldb) </p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>您需要以某种方式确保 ARC 系统不会从内存中删除您的对象。一旦对象的保留计数达到零,ARC 就会删除对象,并且对象不再在范围内。 ARC 系统与垃圾收集器非常不同。您可能想阅读它:<a href="https://developer.apple.com/library/mac/releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html" rel="noreferrer noopener nofollow">https://developer.apple.com/library/mac/releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html</a> </p>
<p>您遇到的错误是未保留 ViewController(<code>WritingViewController</code>) 的结果。尝试在创建 ViewController 的类上创建一个属性:</p>
<pre><code>@property (nonatomic,strong) WritingViewController *writtingVc;
</code></pre>
<p>并在您创建它之后立即将其设置为您的 WritingViewController 实例。</p></p>
<p style="font-size: 20px;">关于ios - 为什么这个委托(delegate)不适用于 UITextView,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/19754253/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/19754253/
</a>
</p>
页:
[1]