自定义委派方法不适用于iOS

时间:2013-04-03 20:02:02

标签: ios objective-c xcode

我创建了一个自定义委托方法来更新ViewController的背景颜色。我无法得到委托方法来回应。这是我的代码:

VASettingsView.h

#import <UIKit/UIKit.h>
#import <GLKit/GLKit.h>

@class VASettingsView;

@protocol VASettingsViewDelegate <NSObject>
- (void)setNewBackgroundColour:(GLKVector4)newColour;
@end

@interface VASettingsView : UIView {
    id <VASettingsViewDelegate> delegate;
}

@property (strong, nonatomic) IBOutlet UIButton *blackBackgroundButton;
@property (strong, nonatomic) IBOutlet UIButton *saveButton;

@property GLKVector4 backgroundColourSetting;

// Set delegate method
@property (nonatomic,weak)id delegate;

- (IBAction)blackButtonPressed:(id)sender;
- (IBAction)saveButtonPressed:(id)sender;

@end

VASettingsView.m

#import "VASettingsView.h"

@implementation VASettingsView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

    }
    return self;
}

- (IBAction)blackButtonPressed:(id)sender {
    self.backgroundColourSetting = GLKVector4Make(0.0, 0.0, 0.0, 0.0);
}
- (IBAction)saveButtonPressed:(id)sender {
    [delegate setNewBackgroundColour:self.backgroundColourSetting];
}

@end

VARendererViewController.h

@class VA_CASFrame;
@class VA_Character;
@class VA_Orbit_Camera;

#import <UIKit/UIKit.h>
#import <GLKit/GLKit.h>
#import <QuartzCore/QuartzCore.h>
#import "VASettingsView.h"

@interface VARendererViewController : GLKViewController <VASettingsViewDelegate>
{
    // Code

}

VARendererViewController.m

viewDidLoad中

// Setup UIView to be delegate
VASettingsView *settingsView = [[VASettingsView alloc] init];
settingsView.delegate = self;

setNewBackgroundColour

- (void)setNewBackgroundColour:(GLKVector4)newColour{

    self.backgroundColour = GLKVector4Make(newColour.x,
                                           newColour.y,
                                           newColour.z,
                                           newColour.w
                                           );
    NSLog(@"STOP");
}

故事板:

Container and UIView

我无法访问setNewBackgroundColour并且一直在寻找几小时的答案。我看不出我做错了什么?

萨姆

3 个答案:

答案 0 :(得分:7)

我怀疑问题是你在VARendererViewController中初始化了一个新的VASettingsView实例,而不是让你的指针放在屏幕上。由于您没有显示如何在屏幕上显示VASettingsView,或者您如何创建其视图,因此只能猜测。

编辑后:

而不是,

VASettingsView *settingsView = [[VASettingsView alloc] init];
settingsView.delegate = self;

试试这个,

VASettingsView *settingsView = self.childViewControllers[0];
SettingsView.delegate = self;

答案 1 :(得分:1)

如果您使用的是iOS 6.0 SDK,则问题可能是委托属性未链接到实例变量delegate。 Apple更改了标准,因此如果您没有@synthesize该属性,则相应的实例变量将被称为_delegate

要解决您的问题,请尝试综合delegate属性或通过self.delegate方法调用saveButtonPressed:来访问该属性。

答案 2 :(得分:0)

您的问题是您在方法中声明了一个局部变量,并设置了它的委托。退出viewDidLoad时,该变量消失。您需要将VASettingsView *settingsView设为实例变量(即在实现中声明它),然后在viewDidLoad中设置其委托。