3

我试图了解如何复制其中包含一组 uibutton 的 uiview。

一直在尝试关注这个问题/答案,但我真的很困惑 atm:

制作 UIView 及其所有子视图的深层副本

基本上试图制作一个显示两组带有按钮的uiviews的vc。这是常规视图的外观:

Points of team 1:
   +  +  +  +
   1  2  3  P
   -  -  -  


Points of team 2:
   +  +  +  +
   1  2  3  P
   -  -  -  

我需要复制它。我可能只是将对象拖到视图控制器上,但如果我创建另一个副本,它将有太多的 IBactions。

关于如何处理这个问题的想法?

编辑: 这就是我解决添加多个按钮的方法

以编程方式向视图添加多个按钮,调用相同的方法,确定它是哪个按钮

4

1 回答 1

3

首先,我会创建一个 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。它不适用于我在这里展示的方式。

于 2013-05-16T13:52:04.973 回答