使用自定义数据

时间:2015-07-28 15:21:35

标签: ios objective-c uiview

我有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];

我的问题:

如何将NSStringNSDate传递到我的DogBoneView实例中?我应该在DogBoneView中创建setter并在初始化实例后调用DogViewController中的setter吗?我应该在init中创建某种新的DogBoneView方法吗?我应该制作dogMessageLabel的标签dogDateLabelDogBoneView公共属性吗?这里的最佳做法是什么?

1 个答案:

答案 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).