【发布时间】:2014-05-18 07:14:22
【问题描述】:
我是 iOS 编程的新手,我正在尝试学习如何在不使用 storyboard 的情况下向视图添加标签和按钮。然而,这对我来说并不顺利。我没有收到任何错误,但运行代码时我的对象都没有显示。
这是我的 .h 文件:
@interface SomeViewController : UIViewController
@property (weak, nonatomic) UILabel *quoteLabel;
@property (weak, nonatomic) UIButton *helloButton;
@end
这是我的 .m 文件中的代码:
- (void)loadView {
[super loadView];
// Should i override this loadView in order to add more graphical elements? How would i do that?
// Creating a view here which i thought i could add my button and label to.
// Is this the right way to go or is it unnecessary?
UIView *contentView = [[UIView alloc] init];
contentView.backgroundColor = [UIColor whiteColor];
self.view = contentView;
// Creating my buttonWithType
// (does this also make my button allocated and initiated or do i need to do that manually?)
// Is this unnecessary considering iOS 7's default buttons is just a text?
self.helloButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
self.helloButton.frame = CGRectMake(100.0, 35.0, 120.0, 30.0);
[self.helloButton setTitle:@"Hello" forState:UIControlStateNormal];
[self.helloButton addTarget:self
action:@selector(helloButtonPressed)
forControlEvents:UIControlEventTouchUpInside];
self.helloButton.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
// Try to add this button to the view, but it won't show.
[contentView addSubview:self.helloButton];
// Same issue for my label object.
self.quoteLabel.frame = CGRectMake(55.0, 85.0, 210.0, 21.0);
self.quoteLabel.textAlignment = NSTextAlignmentCenter;
self.quoteLabel.textColor = [UIColor whiteColor];
self.quoteLabel.backgroundColor = [UIColor blackColor];
self.quoteLabel.font = [UIFont fontWithName:@"System" size:(17.0)];
self.quoteLabel.text = @"Test";
// Trying to add it to the contentView
[contentView addSubview:self.quoteLabel];
我非常想知道如何将那些在 .h 中声明为属性的元素添加到视图中。执行以下操作:
UILabel *someLabel = [ [UILabel alloc ] initWithFrame:CGRectMake(55.0, 85.0, 210.0, 21.0) ];
someLabel.textAlignment = NSTextAlignmentCenter;
someLabel.textColor = [UIColor whiteColor];
someLabel.backgroundColor = [UIColor blackColor];
someLabel.font = [UIFont fontWithName:@"System" size:(18.0)];
[contentView addSubview:someLabel];
someLabel.text = @"Test";
已经可以正常使用了。
【问题讨论】:
-
如果改变contentview的backgroundcolor,能看到吗?
-
@DovD。是的,我可以看到它。 :)
-
可能需要在添加其他视图后设置self.view,或者添加子视图后刷新视图。
-
为什么在这里使用弱引用?试试强吧。
标签: ios objective-c ios7 storyboard uilabel