我想补充一下答案。我希望人们会改进这个答案。
首先它确实有效。
XIB:
结果:
我很想继承 UIView 很长一段时间,尤其是 tableViewCell。
我就是这样做的。
这是成功的,但在我看来,有些部分仍然“尴尬”。
首先,我创建了一个常用的 .h、.m 和 xib 文件。请注意,如果您创建的子类不是 UIViewController 的子类,Apple 没有自动创建 xib 的复选框。无论如何都要创建它们。
#import <UIKit/UIKit.h>
#import "Business.h"
@interface BGUIBusinessCellForDisplay : UITableViewCell
+ (NSString *) reuseIdentifier;
- (BGUIBusinessCellForDisplay *) initWithBiz: (Business *) biz;
@end
非常简单的 UITableViewCell,我想用 biz 初始化后者。
我把你应该为 UITableViewCell 做的重用标识符放了
//#import "Business.h"
@interface BGUIBusinessCellForDisplay ()
@property (weak, nonatomic) IBOutlet UILabel *Title;
@property (weak, nonatomic) IBOutlet UIImageView *Image;
@property (weak, nonatomic) IBOutlet UILabel *Address;
@property (weak, nonatomic) IBOutlet UILabel *DistanceLabel;
@property (weak, nonatomic) IBOutlet UILabel *PinNumber;
@property (strong, nonatomic) IBOutlet BGUIBusinessCellForDisplay *view;
@property (weak, nonatomic) IBOutlet UIImageView *ArrowDirection;
@property (weak, nonatomic) Business * biz;
@end
@implementation BGUIBusinessCellForDisplay
- (NSString *) reuseIdentifier {
return [[self class] reuseIdentifier];
};
+ (NSString *) reuseIdentifier {
return NSStringFromClass([self class]);
};
然后我删除了大多数初始化代码并改为:
- (BGUIBusinessCellForDisplay *) initWithBiz: (Business *) biz
{
if (self.biz == nil) //First time set up
{
self = [super init]; //If use dequeueReusableCellWithIdentifier then I shouldn't change the address self points to right
NSString * className = NSStringFromClass([self class]);
//PO (className);
[[NSBundle mainBundle] loadNibNamed:className owner:self options:nil];
[self addSubview:self.view]; //What is this for? self.view is of type BGCRBusinessForDisplay2. That view should be self, not one of it's subview Things don't work without it though
}
if (biz==nil)
{
return self;
}
self.biz = biz;
self.Title.text = biz.Title; //Let's set this one thing first
self.Address.text=biz.ShortenedAddress;
//if([self.distance isNotEmpty]){
self.DistanceLabel.text=[NSString stringWithFormat:@"%dm",[biz.Distance intValue]];
self.PinNumber.text =biz.StringPinLineAndNumber;
请注意,这真的很尴尬。
首先,init 可以有两种使用方式。
- 可以直接用在aloc之后
- 如果我们有另一个现有的类,然后我们只想将该 现有 单元格初始化到另一个业务,则可以使用它。
所以我做到了:
if (self.biz == nil) //First time set up
{
self = [super init]; //If use dequeueReusableCellWithIdentifier then I shouldn't change the address self points to right
NSString * className = NSStringFromClass([self class]);
//PO (className);
[[NSBundle mainBundle] loadNibNamed:className owner:self options:nil];
[self addSubview:self.view]; //What is this for? self.view is of type BGCRBusinessForDisplay2. That view should be self, not one of it's subview Things don't work without it though
}
我做的另一件令人讨厌的事情是当我做 [self addSubview:self.view];
问题是我希望自己成为 视图。不是self.view。不知何故,它仍然有效。所以是的,请帮助我改进,但这本质上是实现您自己的 UIView 子类的方式。