我想在我的viewcontroller上多次使用一個xib文件(這只是一個簡單的視圖)。我可以將它添加到我的viewcontroller不止一次,並與它們進行交互。問題是,我如何區分這些視圖來知道我點擊哪一個?如何在多個視圖中調用相同的xib,但區分哪些是我正在進行交互?
例如,當我在我的firstView挖掘,我想打印「蘋果」當我在第二視圖點擊i灣打印「橘子」
下面你可以看到我的代碼,這裏是GitHub庫https://github.com/TimurAykutYildirim/demoView/tree/multiple-instance
ViewController.h
#import <UIKit/UIKit.h>
#import "Mini.h"
@interface ViewController : UIViewController <SelectionProtocol>
@property (weak, nonatomic) IBOutlet Mini *miniView;
@property (weak, nonatomic) IBOutlet Mini *miniView2;
@end
ViewController.m
0:爲你我的代碼玩#import "ViewController.h"
@interface ViewController()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.miniView.delegate = self;
self.miniView2.delegate = self;
}
-(void) isClicked {
NSLog(@"apples");
NSString * storyboardName = @"Main";
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil];
UIViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"SecondViewController"];
[self presentViewController:vc animated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
Mini.h
#import <UIKit/UIKit.h>
@protocol SelectionProtocol;
@interface Mini : UIView
@property (nonatomic, weak) id<SelectionProtocol> delegate;
- (IBAction)btnClick:(id)sender;
@end
@protocol SelectionProtocol <NSObject>
@required
-(void) isClicked;
@end
Mini.m
#import "Mini.h"
@implementation Mini
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
if (self = [super initWithCoder:aDecoder]) {
[self load];
}
return self;
}
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
[self load];
}
return self;
}
- (void)load {
UIView *view = [[[NSBundle bundleForClass:[self class]] loadNibNamed:@"Mini" owner:self options:nil] firstObject];
[self addSubview:view];
view.frame = self.bounds;
}
- (IBAction)btnClick:(id)sender {
if ([self.delegate conformsToProtocol:@protocol(SelectionProtocol)]) {
[self.delegate isClicked];
}
}
@end
您可以爲每個視圖使用不同的標記。用協議方法發送標籤。我認爲它會爲你工作。 –