2013-01-19 43 views
0

我想创建一个自定义UIView类,根据某些输入将显示动态数量的UISegmentedControl对象。例如,如果客户的购物车中有5件商品,则UIView应生成5个UISegmentedControl对象,然后我将与每件商品链接。iOS:在UIView中动态创建UISegmentedControl

我遇到的问题是让此工作在UIView。这是我迄今为止所做的。我成功地创建了一个UISegmentedControl对象并以编程方式将其显示在我的主要UIViewController中。将它添加到我的UIView课程时,我没有任何显示。下面是UIView类的实现代码:

#import "ajdSegmentView.h" 

@implementation ajdSegmentView 

- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
     // Initialization code 
     NSArray *itemArray = [NSArray arrayWithObjects:@"Yes", @"No", nil]; 

     UISegmentedControl *button = [[UISegmentedControl alloc] initWithItems:itemArray]; 
     button.frame = CGRectMake(35,44, 120,44); 
     button.segmentedControlStyle = UISegmentedControlStylePlain; 
     button.selectedSegmentIndex = 1; 

     [self addSubview:button]; 
    } 
    return self; 
} 
@end 

我通过故事板创建了一个新UIView对象,并把它放在UIViewController场景里面。我确保将类从通用UIView类设置为我的新自定义类。我在UIViewController课中增加了UIView的插座。这里是UIViewController里面执行代码:

#import "ajdViewController.h" 

@interface ajdViewController() 

@end 

@implementation ajdViewController 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 

    self.segmentView = [[ajdSegmentView alloc] init]; 
} 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

@end 

这就是我都试过了。我一直在寻找很多页面,并试图在不询问这里的情况下实现这一点,但我似乎正在寻找错误的地方。

+0

您是否在调试器中验证过'initWithFrame:'被调用? –

回答

0

您正在使用init方法初始化您的自定义视图,但是您的ajdSegmentView的初始化位于您的initWithFrame:方法中(在您的情况下未调用该方法)。

所以更换:

self.segmentView = [[ajdSegmentView alloc] init]; 

有:

// Change the frame to what you want 
self.segmentView = [[ajdSegmentView alloc] initWithFrame:CGRectMake(0,0,100,40)]; 

也不要忘记您的视图添加到视图控制器的看法也。

[self.view addSubview:self.segmentView]; 

除非这一观点正与界面生成器,在这种情况下,你需要在你的ajdSegmentView类重写initWithCoder:创建。

虽然我并不熟悉Storyboard,但也许我错过了一些东西,但在标准情景中,我上面所说的将解决您的问题。

+0

覆盖'initWithCoder:'做了诀窍。非常感谢你! – Alex

1

首先您需要检查ajdSegmentView是UIVIewUIViewController。如果是UIView,那很好。如果它是UIViewController的类型,那么在添加Segment时需要添加此行。

[self.view addSubview:button]; 

在地方:

[self addSubview:button]; 

还有一件事你忘了分配打完这个视图添加到您的主你可以声明如下:

objajdSegmentView = [[ajdSegmentView alloc] init]; 
[self.view addSubview:objajdSegmentView.view]; 

我刚才添加了这个东西。我得到了这样的结果。enter image description here

希望这会对你有用。

+0

我已经通过Storyboard将'UIView'添加到'UIViewController'。我使用Outlet链接了'UIView'。此时没有任何内容显示在UIView上。 – Alex

+0

如果我选择以编程方式执行所有操作,它会将视图和按钮添加到正确的位置。我所做的是创建了一个新的'ajdSegmentView'对象,并使用'[self.view addSubview:newSegmentView]'将其添加到'UIViewController'中。它显示按钮,但我无法与它交互。 – Alex

+0

您必须添加此方法:[segmentedControl addTarget:self action:@selector(action :) forControlEvents:UIControlEventValueChanged]; – Nirav