2014-10-30 82 views
1

我試圖給UITextView添加下劃線樣式,並且它不適用。如果我使用「陰影」(取消陰影樣式和評論下劃線樣式)我可以看到它,但由於某種原因沒有應用下劃線。我使用「Courier New」字體。NSAttributedString:下劃線不適用

- (void) addDiagHighlighting: (NSMutableAttributedString*)attrString start:(int)start end:(int)end severity:(int)severity { 
    // ignore diags that are out of bounds 
    if (start > attrString.length || end > attrString.length) 
     return; 

    NSRange range = NSMakeRange(start, end - start); 
    UIColor *diagColor = [self getSeverityColor: severity]; 

    // shadow 
// NSShadow *shadow = [[NSShadow alloc] init]; 
// [shadow setShadowColor: diagColor]; 
// [shadow setShadowOffset: CGSizeMake (1.0, 1.0)]; 
// [shadow setShadowBlurRadius: 1.0]; 
// [attrString addAttribute:NSShadowAttributeName 
//      value:shadow 
//      range:range]; 

    // underline 
    [attrString addAttributes:@{ 
           NSUnderlineColorAttributeName : diagColor, // color 
           NSUnderlineStyleAttributeName : @(NSUnderlinePatternSolid) // style 
           } 
         range:range]; 
} 

我可以改變屬性添加到同時添加陰影和下屬,我可以看到影子,但仍然沒有下劃線:

// shadow + underline 
[attrString addAttributes:@{ 
          NSShadowAttributeName : shadow, // shadow 
          NSUnderlineColorAttributeName : diagColor, // color 
          NSUnderlineStyleAttributeName : @(NSUnderlinePatternSolid) // style 
          } 
        range:range]; 

回答

4

您需要或與NSUnderlineStyle一個NSUnderlinePattern得到它的工作(see Apple documentation here

試試這個:

[attrString addAttributes:@{ 
         NSShadowAttributeName : shadow, // shadow 
         NSUnderlineColorAttributeName : diagColor, // color 
         NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle | NSUnderlinePatternSolid) // style 
         } 
       range:range]; 

或用點......

[attrString addAttributes:@{ 
         NSShadowAttributeName : shadow, // shadow 
         NSUnderlineColorAttributeName : diagColor, // color 
         NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle | NSUnderlinePatternDot) // style 
         } 
       range:range]; 
0

蘋果開發人員參考API規定有關NSUnderlineStyle

樣式,圖案,以及可選的字掩碼邏輯或運算,產生價值NSUnderlineStyleAttributeNameNSStrikethroughStyleAttributeName

因此,斯威夫特3和斯威夫特4,你可以使用bitwise OR operator|)設置的風格和圖案一起爲您NSAttributedStringNSUnderlineStyleAttributeName/NSAttributedStringKey.underlineStyle屬性。


以下游樂場代碼顯示如何爲NSAttributedString實例設置兩個NSUnderlineStyleThick/NSUnderlineStyle.styleThickNSUnderlinePatternDot/NSUnderlineStyle.patternDot屬性:

夫特3:

import UIKit 

let attributes = [NSUnderlineStyleAttributeName : NSUnderlineStyle.styleThick.rawValue | NSUnderlineStyle.patternDot.rawValue] 
let attributedString = NSAttributedString(string: "Some text", attributes: attributes) 

夫特4:

import UIKit 

let attributes = [NSAttributedStringKey.underlineStyle : NSUnderlineStyle.styleThick.rawValue | NSUnderlineStyle.patternDot.rawValue] 
let attributedString = NSAttributedString(string: "Some text", attributes: attributes)