![](/img/trans.png)
[英]Errors in (void)drawRect:(CGRect)rect iOS 5.1 OpenGL ES 2.0
[英]UITextField - (void)drawPlaceholderInRect:(CGRect)rect returns different CGRect height in iOS 7
我試圖將UITextField
子類化為繪制自定義placehoder。 在iOS 6
這種方法很好但在iOS 7
我得到了不同的CGRect
高度。
UITextField
框架為(0, 0, 500, 45)
UITextField
(0, 0, 500, 45)
。 我通過覆蓋- (CGRect)editingRectForBounds:(CGRect)bounds;
添加了20左邊的填充- (CGRect)editingRectForBounds:(CGRect)bounds;
- (CGRect)placeholderRectForBounds:(CGRect)bounds;
- (CGRect)textRectForBounds:(CGRect)bounds;
調用以下方法:
- (CGRect)makeRectFromBounds:(CGRect)bounds
withTopPadding:(CGFloat)topPadding
andLeftPadding:(CGFloat)leftPadding
{
return UIEdgeInsetsInsetRect(bounds, UIEdgeInsetsMake(topPadding, leftPadding, 0, 0));
}
因為我想要一個不同的placeHolder文本顏色,我覆蓋
- (void)drawPlaceholderInRect:(CGRect)rect
- (void)drawPlaceholderInRect:(CGRect)rect {
[[UIColor colorWithRed:121.0/255.0
green:113.0/255.0
blue:107.0/255.0
alpha:1.0] setFill];
[self printRect:rect from:__FUNCTION__];
[[self placeholder] drawInRect:rect withFont:self.font];
}
我正在打印的矩形如下:
iOS 7: -Rect (X: 0.0, Y:0.0, W:480.0, H:44.0)
iOS 6: -Rect (X: 0.0, Y:0.0, W:480.0, H:26.0)
不知道這是一個錯誤還是我做錯了什么?
請改用以下內容:
[textfield setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
在iOS 7中, contentVerticalAlignment
的默認值從“top”更改為“center”(沒有我可以看到的文檔)。 在“中心”模式下,iOS會在繪制之前調整rectForBounds
方法的結果。 在覆蓋任何textRectForBounds
方法時,您應該設置contentVerticalAlignment = UIControlContentVerticalAlignmentTop
,以便iOS將完全按照指定使用rect。
由於iOS7現在是新的,所以很多人都面臨着iOS7的框架問題。
對於所有這些人,我只想說它很容易,iOS7沒有任何問題。 這只是因為您不知道如何從Apple提供的最新操作系統功能中獲益。
@Cyupa:您只需要應用自動調整大小並屏蔽您的文本字段。
它可能是以下一個或多個。
如果您在文本字段中應用適當的自動調整遮罩,您將獲得所需的視圖框架(此處為textfield)
我也遇到了這個問題,還沒找到原因,但是如果你想在iOS6和iOS7上都有相同的行為,你可以試試這個:
- (CGRect)textRectForBounds:(CGRect)bounds {
CGRect rect = [super textRectForBounds:bounds];
rect = CGRectMake(20, rect.origin.y-4, rect.size.width-20, rect.size.height);
return rect;
}
你可能需要設置:
theLabel.contentVerticalAlignment =UIControlContentVerticalAlignmentCenter;
檢查系統版本並返回UIEdgeInsetsInsetRect(bounds, UIEdgeInsetsMake(topPadding, leftPadding, 0, 0));
你可以檢查設備版本
if(([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0))
{
}
我通過使用此屬性解決了問題
textField.contentVerticalAlignment =UIControlContentVerticalAlignmentCenter;
它適用於iOS6和iOS7。
Ricky的解決方案對我有用,添加此值必須在每次占位符文本更改后設置。 我覆蓋了setPlaceholder來做到這一點。
它取代了覆蓋drawPlaceholderInRect的需要,如果你想要另一個占位符顏色,因此垂直對齊將自動正確。 當然,這並沒有回答這個問題,為什么IOS 7.0表現得那樣,但它可能會解決你的實際問題。
- (void) setPlaceholder: (NSString*)placeholderText {
[super setPlaceholder:placeholderText];
[self setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
}
應該提到的是,有些人不鼓勵繞過公共接口,所以請自行承擔風險! 另請參閱:以編程方式更改UITextField的占位符文本顏色
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.