iOS:在UIView中动态创建UISegmentedControl
我想创建一个自定义的iOS:在UIView中动态创建UISegmentedControl,ios,objective-c,Ios,Objective C,我想创建一个自定义的UIView类,根据一些输入显示动态数量的UISegmentedControl对象。例如,如果一个客户的购物车中有5个产品,UIView应该生成5个UISegmentedControl对象,然后我将与每个项目链接 我遇到的问题是如何在UIView中工作。以下是我迄今为止所做的工作。我成功地创建了UISegmentedControl对象,并在主UIViewController中以编程方式显示它。将其添加到我的UIView类时,我没有得到任何显示。以下是UIView类的实现代码:
UIView
类,根据一些输入显示动态数量的UISegmentedControl
对象。例如,如果一个客户的购物车中有5个产品,UIView
应该生成5个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
场景中。我确保将类从genericUIView
类设置为我的新自定义类。我在我的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
这就是我所尝试的。我已经搜索了很多页面,并试图在这里实现它,但我似乎找错了地方。您正在使用
init
方法初始化自定义视图,但是您对ajdSegmentView的初始化在initWithFrame:
方法中(在您的情况下,不会接到电话)
因此,请替换:
self.segmentView = [[ajdSegmentView alloc] init];
与:
另外,也不要忘记将视图添加到视图控制器的视图中
[self.view addSubview:self.segmentView];
除非此视图是使用interface builder创建的,否则在这种情况下,您需要在ajdSegmentView类中重写initWithCoder:
虽然我不熟悉故事板,所以可能我遗漏了一些东西,但在标准场景中,我上面所说的将解决您的问题。首先您需要检查ajdSegmentView是
UIVIew
还是UIViewController
。如果是UIVIew
,则可以。如果是UIViewController类型,则需要添加此项添加段时,请单击“行”
[self.view addSubview:button];
代替:
[self addSubview:button];
还有一件事,您在分配后忘记将此视图添加到主视图中,以便可以这样声明:
objajdSegmentView = [[ajdSegmentView alloc] init];
[self.view addSubview:objajdSegmentView.view];
我刚刚添加了这个东西,我这样得到了结果
希望这对您有用。您是否在调试器中验证调用了
initWithFrame:
?我已经通过脚本将UIView
添加到UIViewController
中。我使用一个出口链接了UIView
。此时UIView上没有显示任何内容。如果我选择以编程方式执行所有操作只需添加视图和按钮即可。我所做的是创建一个新的ajdSegmentView
对象,并使用[self.view addSubview:newSegmentView]
将其添加到UIViewController
。它显示了按钮,但我无法与之交互。您必须添加此方法:[segmentedControl addTarget:self action:@selector(action:)forControlEvents:UIControlEventValueChanged];您可以在启动分段时在ajdViewController类中添加此方法。重写initWithCoder:
成功。非常感谢!
objajdSegmentView = [[ajdSegmentView alloc] init];
[self.view addSubview:objajdSegmentView.view];