为什么我不需要在标题中声明UIAlertViewDelegate? [英] Why do I not need to declare UIAlertViewDelegate in the header?

查看:190
本文介绍了为什么我不需要在标题中声明UIAlertViewDelegate?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以为我终于设法了解代理的概念,直到发生以下情况:我更改了头文件以删除对代理的引用,并且Alert仍然工作。唯一的区别是我丢失代码提示。

  //。h 
#import< UIKit / UIKit.h>
// @ interface ViewController:UIViewController< UIAlertViewDelegate>
@interface ViewController:UIViewController
- (IBAction)showMessage:(id)sender;
@end

//.m
#importViewController.h
@implementation ViewController
- (IBAction)showMessage:(id)sender {
UIAlertView * message = [[UIAlertView alloc] initWithTitle:@Hello World!
消息:@消息。
delegate:self
cancelButtonTitle:@取消
otherButtonTitles:@Button 1,@Button 2,nil];
[message show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString * title = [alertView buttonTitleAtIndex:buttonIndex];

if([title isEqualToString:@Button 1])
{
NSLog(@1已选中);
}
}
@end


解决方案

您的标题中的< UIAlertViewDelegate> 只是指示您打算在类中实现委托方法的编译器。如果不执行标记为@required的委托方法,则会收到警告,但是由于大多数委托方法通常都是@optional,代码将被编译并运行正常。这并不意味着您不应该在标题中添加代理。


I thought I had finally managed to understand the concept of a delegate until the following occurred: I changed my header file to remove the reference to the delegate and the Alert still worked. The only difference is that I lose code hinting.

//.h
#import <UIKit/UIKit.h>
//@interface ViewController : UIViewController <UIAlertViewDelegate> 
@interface ViewController : UIViewController 
- (IBAction)showMessage:(id)sender;
@end

//.m
#import "ViewController.h"
@implementation ViewController
- (IBAction)showMessage:(id)sender {
    UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Hello World!" 
                                                      message:@"Message." 
                                                     delegate:self 
                                            cancelButtonTitle:@"Cancel" 
                                            otherButtonTitles:@"Button 1", @"Button 2", nil];
    [message show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *title = [alertView buttonTitleAtIndex:buttonIndex];

    if([title isEqualToString:@"Button 1"])
    {
        NSLog(@"Button 1 was selected.");
    }   
}
@end

解决方案

The <UIAlertViewDelegate> in your header is just an indication to the compiler that you intend to implement the delegate methods in your class. You will get warnings if you don't implement delegate methods that are marked as @required, but since most of the delegate methods are usually @optional your code will compile and run fine. That doesn't mean that you shouldn't add the delegates in your header though.

这篇关于为什么我不需要在标题中声明UIAlertViewDelegate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆