2013-09-22 44 views
7

看來UIPickerView不再支持使用NSAttributedString作爲拾取器視圖項目。任何人都可以確認嗎?我在UIPickerView.h文件中發現了NS_AVAILABLE_IOS(6_0),但這是問題嗎?有沒有辦法解決這個問題,還是我運氣不好?UIPickerView:NSAttributedString不適用於iOS 7?

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component; 
- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component NS_AVAILABLE_IOS(6_0); // attributed title is favored if both methods are implemented 
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view; 
+1

當您提供屬性字符串時會發生什麼?它如何不被支持? – Wain

+1

我的歉意我可能應該提到這一點。它運行得很好,但pickerView不會在iOS 7上顯示指定的字體。它只使用系統默認值。在iOS 6上,它顯示在它應該顯示的字體中。 – Rob

+1

您是否嘗試使用屬性文本作爲替代方法返回標籤? – Wain

回答

13

唯一的解決這個問題顯然是使用pickerView:viewForRow:forComponent:reusingView:,並與屬性文本返回一個UILabel,因爲蘋果已經使用歸因串否則顯然無效。

+1

這種方法唯一的問題是選擇器視圖中的視圖在選中時沒有得到好的縮放效果,但是字符串可以。 – Indoor

+0

我同意,我不確定實際上有一種方法可以自己實現它。蘋果公司再次破壞自己的代碼是一個不幸的問題。 – Rob

7

Rob是正確的,錯誤或不是在iOS 7 UIPickerView中獲取屬性文本的最簡單方法是破解pickerView:viewForRow:forComponent:reusingView:方法。這是我沒有...

-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view 
{ 
    // create attributed string 
    NSString *yourString = @"a string"; //can also use array[row] to get string 
    NSDictionary *attributeDict = @{NSForegroundColorAttributeName : [UIColor whiteColor]}; 
    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:yourString attributes:attributeDict]; 

    // add the string to a label's attributedText property 
    UILabel *labelView = [[UILabel alloc] init]; 
    labelView.attributedText = attributedString; 

    // return the label 
    return labelView; 
} 

它看起來iOS上的7大,但在iOS 6中的默認背景是白色的,所以你不能看到我的白色文字。我建議檢查iOS版本並根據每個版本實施不同的屬性。

+1

https://github.com/erica/iOS-6-Advanced-Cookbook/tree/master/C01%20-%20Device/02%20-%20UIDevice-Hardware 這是一個很好的圖書館,用於檢查只是關於設備的一切。抓住UIDevice-Hardware.h – Rob

4

下面是使用pickerView:viewForRow:forComponent:reusingView:以尊重再循環視圖的方式示例。

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UILabel *)recycledLabel { 
    UILabel *label = recycledLabel; 
    if (!label) { // Make a new label if necessary. 
     label = [[UILabel alloc] init]; 
     label.backgroundColor = [UIColor clearColor]; 
     label.textAlignment = NSTextAlignmentCenter; 
    } 
    label.text = [self myPickerTitleForRow:row forComponent:component]; 
    return label; 
}