2011-02-15 39 views
0

我想分類UIView並將四個UILabel放在另一個上面;頂部標籤將是MASK,第二個標籤將是帶有文本的正常標籤,第三個標籤是帶有沒有文本的純色背景的標籤。底部標籤將與具有不同顏色字體的頂部第二個標籤相同。當我發送第三個標籤的寬度時,它會覆蓋顯示文本部分視圖的底部標籤。我希望第二個文本是一種顏色,而底層標籤顯示另一種顏色的字體。如何在iOS中掩蓋UILabel - Objective-C

這是possibe?如果有人可以解釋如何掩蓋在Objective-C中,這也將有所幫助。

我試圖構建一個UIView,就像一個進度條,當條形填充到60%時,我希望頂部文本以白色字體顏色顯示,當底部文本以不同顏色顯示時。

+0

我有種方式使用UILineBreakModeClip並將標籤放在彼此的頂部。但剪輯似乎放棄了最後一封信;我認爲這是假設剪輯矩形結束的地方。我想呈現「W」的一半 – Arcadian 2011-02-15 21:45:02

回答

1

您可以使用兩個UILabels,一個在底部,另一個嵌入頂部的另一個視圖。

UILabel *bottomLabel = ...; 
[self.view addSubview:bottomLabel]; 

UIView *topContainer = [[UIView alloc] initWithFrame:bottomLabel.frame]; 
topContainer.clipsToBounds = YES; 
topContainer.opaque = NO; 
topContainer.backgroundColor = [UIColor clearColor]; 

UILabel *topLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, bottomLabel.frame.size.width, bottomLabel.frame.size.height)]; 
topLabel.text = bottomLabel.text; 
topLabel.opaque = NO; 
topLabel.backgroundColor = [UIColor clearColor]; 

[topContainer addSubview:topLabel]; 
[self.view addSubview:topContainer]; 

然後,當您要更改進度時,您將設置的寬度爲topContainer。這應該剪輯topLabel

0

而不是使用四個UILabel,爲什麼不將子類UILabel自己繪製在drawRect:方法中?它看起來像這樣:

- (void)drawRect:(CGRect)rect { 
    CGContextRef context = UIGraphicsGetCurrentContext(); 

    // Set the mask 
    CGContextClipToMask(context, self.bounds, /* mask image */); 

    // Draw the text in a different font 
    [self.text drawInRect:rect withFont:/* alternate font */]; 

    // Draw a solid background 
    CGContextSetRGBFillColor(context, ...); 
    CGContextFillRect(context, rect); 

    // Draw the text normally 
    [super drawRect:rect]; 
} 

爲方便起見,您可以製作遮罩圖像和子類的備用字體屬性。

+0

這是否允許部分字符呈現?目標是確保如果進度條位於字符之間,那麼角色應該顯示兩種顏色。 – Arcadian 2011-02-16 17:29:23

+1

您可能想要在CGContextClipToMask中使用self.bounds,而不是self.frame。 – titaniumdecoy 2011-03-30 01:22:38