首先,我会创建一个 UIView 子类,称为 PointsView 或其他东西。
这看起来像这样......
Points of [name label]:
+ + + +
1 2 3 P
- - -
它将具有类似NSString *teamName
的属性,并根据相关标签设置这些属性。
它还可能具有属性,NSUInteger score
因此您可以设置 PointView 对象的得分值。
这完全与您的 UIViewController 分开。
现在,在您的 UIViewController 子类中,您可以执行类似...
PointsView *view1 = [[PointsView alloc] initWithFrame:view1Frame];
view1.teamName = @"Team 1";
view1.score1 = 1;
view1.score2 = 2;
view1.score3 = 3;
[self.view addSubView:view1];
PointsView *view2 = [[PointsView alloc] initWithFrame:view2Frame];
view2.teamName = @"Team 2";
view2.score1 = 1;
view2.score2 = 2;
view2.score3 = 3;
[self.view addSubView:view2];
现在不涉及复制。您只需创建一个对象的两个实例。
编辑
创建您的视图子类...
创建视图子类的最简单方法是执行以下操作...
创建文件... PointsView.m 和 PointsView.h
.h 文件看起来像这样......
#import <UIKit/UIKit.h>
@interface PointsView : UIView
@property (nonatomic, strong) UILabel *teamNameLabel;
// other properties go here...
@end
.m 看起来像这样......
#import "PointsView.h"
@implementation PointsView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.teamNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 21)];
self.teamNameLabel.backgroundColor = [UIColor clearColor];
[self addSubView:self.teamNameLabel];
// set up other UI elements here...
}
return self;
}
@end
然后在您的视图控制器中,您将 PointsView 添加到它的代码中(即不使用界面生成器),就像这样......
- (void)viewDidLoad
{
[super viewDidLoad];
PointsView *pointsView1 = [[PointsView alloc] initWithFrame:CGRectMake(0, 0, 320, 200)];
pointsView1.teamNameLabel.text = @"Team 1";
[self.view addSubView:pointsView1];
// add the second one here...
}
您也可以在 Interface Builder 中创建和添加这些视图,但在这里解释起来要困难得多。
如果您以这种方式设置它,那么您可以使用 IB 来设置 UIViewController 的其余部分。只是不要使用 IB 来设置 PointsViews。它不适用于我在这里展示的方式。