我们有一个窗口充满了小视图正方形(想起计算器)。iPhone - 以编程方式在视图中显示单个字符串
因为我们想在视图中显示一个字符串不使用Interface Builder来添加字符串的窗口上的特定视图。 我们需要能够更改字符串并刷新视图。
我们如何通过编程将字符串添加到一个视图,并显示它?
更新:
确定这里是我们目前拥有的代码。头文件中没有什么特别的。 我认为真正的窘境正在考虑我们可以很容易地获得背景颜色来改变,为什么我们的文本没有显示? 这两个版本都在里面,很高兴看到“苹果”或“橙子”。
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
bgString = @"orange";
UILabel* aLabel = [[UILabel alloc] init];
aLabel.text = @"apple";
self.textLabel = aLabel;
[aLabel release];
[self addSubview:textLabel];
}
return self;
}
- (void)drawRect:(CGRect)rect {
// Drawing code
[[UIColor yellowColor] setFill];
UIRectFill(rect);
[self drawStringCenteredIn:rect];
}
- (void)drawStringCenteredIn:(CGRect)r {
//CGSize strSize = [bgString size];
CGPoint strOrigin;
strOrigin.x = r.origin.x; //+ (r.size.width - 10)/2;
strOrigin.y = r.origin.y; //+ (r.size.height - 10)/2;
//[bgString drawAtPoint:strOrigin withFont:[UIFont fontWithName:@"Helvetica" size:10]];
[textLabel drawTextInRect:r];
}
别忘了'[aLabel sizeToFit]' – cobbal 2010-08-31 04:07:46
嗯。也忘了用框架来初始化它 - 希望OP可以采取这种方式并运行它。 – 2010-08-31 04:14:00
感谢大家迄今为止的快速反应。 这将工作得很好,如果我使用ViewController,但我特别想与主视图控制器上的“视图”进行交互。 所以我需要我的代码去drawRect类型的结构。 – Evolve 2010-08-31 04:52:43