我有UIViewController
名为DogViewController.h/.m
。我正在创建一个名为UIView
的自定义DogBoneView.h/.m
,目前看起来像这样:
DogBoneView.h
#import <UIKit/UIKit.h>
@interface DogBoneView : UIView
@end
DogBoneView.m
#import "DogBoneView.h"
@interface DogBoneView ()
@property (nonatomic, strong) UILabel *dogMessageLabel;
@property (nonatomic, strong) UILabel *dogDateLabel;
@end
@implementation DogBoneView
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self setBackgroundColor:[UIColor blueColor]];
// Create labels
self.dogMessageLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, 30)];
self.dogDateLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, frame.size.width, 30)];
}
return self;
}
@end
然后在DogViewController.m
中,我创建了DogBoneView
的实例,如下所示:
DogBoneView *dbv = [[DogBoneView alloc] initWithFrame:CGRectMake(0,0,self.view.frame.size.width,60];
我的问题:
如何将NSString
和NSDate
传递到我的DogBoneView
实例中?我应该在DogBoneView
中创建setter并在初始化实例后调用DogViewController
中的setter吗?我应该在init
中创建某种新的DogBoneView
方法吗?我应该制作dogMessageLabel
的标签dogDateLabel
和DogBoneView
公共属性吗?这里的最佳做法是什么?
答案 0 :(得分:1)
If it is your intent that the NSString
and NSDate
must be set (i.e, it would be a programming error to leave either one unset), then specify an initializer which takes them as arguments, and mark the inherited initWithFrame
as unavailable to force using your initializer:
@interface DogBoneView: UIView
- (nonnull instancetype)initWithFrame:(CGRect)frame __unavailable;
- (nonnull instancetype)initWithFrame:(CGRect)frame
message:(nonnull NSString *)message
date:(nonnull NSDate *)date NS_DESIGNATED_INITIALIZER;
@end
As initWithCoder:
is also a designated initializer of the superclass, you should also override it or mark it, too, as unavailable.
On the other hand, if the string and date can be empty, then just provide the accessors. You could still provide this type of convenience initializer (remove the NS_DESIGNATED_INITIALIZER
in that case).