我們有一個窗口充滿了小視圖正方形(想起計算器)。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