我创建了一个自定义视图并向其中添加了一个 UITextField。我的问题是:如何添加一个委托以便您可以将其设置为 XCode 的默认 cmd+拖动行为?
我目前的尝试是做这样的事情:
在我的 .h 文件中:
#import <UIKit/UIKit.h>
IB_DESIGNABLE
@interface CustomTextField : UIView
@property (assign, nonatomic) IBInspectable id textFieldDelegate;
@end
和我的 .m 文件:
#import "CustomTextField.h"
@interface CustomTextField()
@property (strong, nonatomic) IBOutlet UITextField *textField;
@end
@implementation CustomTextField
- (instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
[self loadNib];
}
return self;
}
- (void)loadNib{
UIView *view = [[[NSBundle bundleForClass:[self class]] loadNibNamed:@"CustomTextField" owner:self options:nil] firstObject];
[self addSubview:view];
view.frame = self.bounds;
}
- (void)setTextFieldDelegate:(id)textFieldDelegate{
self.textField.delegate = textFieldDelegate;
}
@end
但它不会出现在 XCode 的左侧面板中,Connections Inspector 选项卡中。
这也是我当前的代码。
更新1:
如果使用下面的代码,我也会收到错误:
- (id)initWithFrame:(CGRect)aRect
{
self = [super initWithFrame:aRect];
if (self)
{
[self loadNib];
}
return self;
}
- (id)initWithCoder:(NSCoder*)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self)
{
[self loadNib];
}
return self;
}
- (void)loadNib{
//
// UIView *view = [[[NSBundle bundleForClass:[self class]] loadNibNamed:@"CustomTextField" owner:self options:nil] firstObject];
// [self addSubview:view];
// view.frame = self.bounds;
UIView *view = [[[NSBundle bundleForClass:[self class]] loadNibNamed:@"CustomTextField" owner:self options:nil] firstObject];
[view setTranslatesAutoresizingMaskIntoConstraints:NO];
[self addSubview:view];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[view]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(view)]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(view)]];
self.textLabel.text = @"1";
}
关于我应该怎么做的任何建议?
更新 2
我最终将initWithFrame
,initWithCoder
和loadNib
函数替换为:
- (id)awakeAfterUsingCoder:(NSCoder *)aDecoder
{
if (![self.subviews count])
{
NSBundle *mainBundle = [NSBundle mainBundle];
NSArray *loadedViews = [mainBundle loadNibNamed:@"CustomTextField" owner:nil options:nil];
CustomTextField *loadedView = [loadedViews firstObject];
loadedView.frame = self.frame;
loadedView.autoresizingMask = self.autoresizingMask;
loadedView.translatesAutoresizingMaskIntoConstraints =
self.translatesAutoresizingMaskIntoConstraints;
for (NSLayoutConstraint *constraint in self.constraints)
{
id firstItem = constraint.firstItem;
if (firstItem == self)
{
firstItem = loadedView;
}
id secondItem = constraint.secondItem;
if (secondItem == self)
{
secondItem = loadedView;
}
[loadedView addConstraint:
[NSLayoutConstraint constraintWithItem:firstItem
attribute:constraint.firstAttribute
relatedBy:constraint.relation
toItem:secondItem
attribute:constraint.secondAttribute
multiplier:constraint.multiplier
constant:constraint.constant]];
}
return loadedView;
}
return self;
}