[英]Call delegate method (iOS)
我想向您展示我的代碼/故事板的拳頭:
這是我的故事板:我有一個小UISlider和一個UIView。 UIView是一個自定義視圖,其類為“ SquareView”。 這是代碼:
SquareView.h
#import <UIKit/UIKit.h>
@class SquareView;
@protocol SquareViewDelegate <NSObject>
-(int)giveMeTheNumbersOfSquare:(SquareView *)squareView;
@end
@interface SquareView : UIView
@property (nonatomic , weak) IBOutlet id<SquareViewDelegate> delegate;
@end
和SquareView.m
#import "SquareView.h"
@implementation SquareView
@synthesize delegate;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
int numberOfSquare = [delegate giveMeTheNumbersOfSquare:self];
NSLog(@"Value of numberOfSquare in drawRect---> %d" ,numberOfSquare);
//numberOfSquare = 20;
for (int i=0; i<numberOfSquare; i++) {
float x = arc4random() % (int)self.frame.size.width - 20;
float y = arc4random() % (int)self.frame.size.width - 20;
UIRectFill(CGRectMake(x, y, 20.0, 20.0));
// NSLog(@"X---> %f" ,x);
//NSLog(@"Y---> %f" ,y);
[self setNeedsDisplay];
}
// Drawing code
}
@end
現在,ViewController ... ViewController是SquareView的委托。
ViewController.h
#import <UIKit/UIKit.h>
#import "SquareView.h"
@interface TestViewController : UIViewController <SquareViewDelegate>
@property (weak) IBOutlet SquareView *squareView;
@property(weak) IBOutlet UISlider *slider;
-(IBAction)changeSquareNumbers:(id)sender;
@end
和ViewController.m
#import "TestViewController.h"
@interface TestViewController ()
{
int _squareCount;
}
@end
@implementation TestViewController
@synthesize squareView = _squareView;
@synthesize slider = _slider;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)awakeFromNib
{
[_squareView setDelegate:self];
_squareCount = 50;
[self.squareView setNeedsDisplay];
}
/********* Delegate Method *********/
-(int)giveMeTheNumbersOfSquare:(SquareView *)squareView
{
//return _squareCount;
NSLog(@"Value of _squareCount in giveMeTheNumberOfSquare ---> %d" ,_squareCount);
return _squareCount;
}
-(IBAction)changeSquareNumbers:(UISlider *)sender
{
NSLog(@"Value of slider in changeSquareNumbers --> %f" ,[sender value]]);
_squareCount = (int)[sender value];
NSLog(@"Value of _sqareCount ---> %d" ,_squareCount);
[self.squareView setNeedsDisplay];
}
現在...在SquareView.m文件的drawRect函數中,我不知道為什么該程序從不調用“ giveMetheNumbersOfSquare函數。drawRect中的” numberOfSquare“保持為0 !!!我不明白為什么該程序切勿輸入“ giveMeTheNumberOfSquare”函數!
謝謝!!
確保正確設置了委托。 您可能需要分配或初始化squareView。 另外,如果您使用情節提要,則可能不會調用awakeFromNib
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.