【发布时间】:2017-08-03 06:43:30
【问题描述】:
我的 ViewController 正在显示 Xib UIView。 Xib 包含一个 UILabel 和一个 UIButton。我的按钮覆盖在我的 xib 上,我用它来导航我的 SecondViewController,我通过委托方法实现了这一点。
这是关于我的标签的事情;因为我的按钮是透明的,所以我可以在按钮下方显示它。我不能做的是从 ViewController 更改 mylabel 的文本。
我做了一些搜索,发现了这样的建议:
为子视图创建另一个 .nib 文件并将子视图放入 那里。然后在那个 .nib 文件中,使文件所有者为 IOSubview。财产 连接在那里工作得很好。然后只需将子视图添加到 您的 IOViewController 以编程方式。只记得加载笔尖 首先从捆绑包中提取文件。
但这对我来说没有意义,因为我最初创建 xib 的原因是多次使用它。我相信这个问题的解决方案可能会简单得多。但是怎么做??
这是一个 github repo 链接和我的代码:
https://github.com/TimurAykutYildirim/demoView
ViewController.h
#import <UIKit/UIKit.h>
#import "Mini.h"
@interface ViewController : UIViewController <SelectionProtocol>
@property (weak, nonatomic) IBOutlet Mini *miniView;
@property (weak, nonatomic) IBOutlet UILabel *miniLabel;
@end
ViewController.m
#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;
}
-(void) isClicked {
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
迷你.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
最小.m
#import "Mini.h"
@implementation Mini
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
- (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;
// ui component properties will be set here
}
- (IBAction)btnClick:(id)sender {
if ([self.delegate conformsToProtocol:@protocol(SelectionProtocol)]) {
[self.delegate isClicked];
}
}
@end
【问题讨论】:
-
您需要将 UILabel 注入到您的 UIView 类中,在您的情况下是“Mini”类。
标签: ios objective-c uiview uiviewcontroller iboutlet