2017-04-19 96 views
1

我試圖從一組定義中顯示文本到視圖,並且在文本/字符串有括號的情況下,我想以不同的方式顯示該括號元素 - 讓我們說粗體與非粗體。Swift - 將屬性字符串添加到括號中的項目

這串

這串B(括號有)」 - 括號顯示在較低 重量字體

現在我知道該解決方案是通過將正則表達式 - \(\w*\) - 與歸因字符串結合使用而發現的,但我無法將其有效地組合。

這是我的功能,打印的話

func setWord(_ index:Int) { 
    if (index < 0) { return } 
    let word:[String:AnyObject] = self.definitions[index] 
    if let wordLabelText = word[self.store.sourceLanguage.lowercased()] as? String { 
     self.wordLabel.attributedText = NSMutableAttributedString(string: wordLabelText, attributes: [NSKernAttributeName: 1.0]) 
    } 
    print(word) 
    self.definitionView.word = word 
} 

我到目前爲止所做的是增加了對歸因串輸出一些定義,但當時我不知道如何繼續:

func setWord(_ index:Int) { 
    if (index < 0) { return } 
    let font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline) 
    let fontSize = font.pointSize * 3 
    let plainFont = UIFont(name: "X-BoldItalic", size: fontSize) 
    let boldFont = UIFont(name: "X-Italic", size: fontSize) 
    let word:[String:AnyObject] = self.definitions[index] 
    if let wordLabelText = word[self.store.sourceLanguage.lowercased()] as? String { 
     self.wordLabel.attributedText = NSMutableAttributedString(string: wordLabelText, attributes: [NSKernAttributeName: 1.0, NSFontAttributeName: boldFont]) 

在這裏,我需要循環查找(元素)的單詞,但我不知道如何做到這一點,並正確地返回單詞。我在正確的道路上嗎?謝謝你:)

回答

1

Objective-C中的解決方案,解釋了在Swift中應該很容易翻譯的邏輯。

NSDictionary *defaultAttributes = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:15]}; 
NSDictionary *otherAttributes = @{NSFontAttributeName: [UIFont systemFontOfSize:12]}; 

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\(.*?\\)" options:0 error:nil]; 
NSString *initialString = @"This string a (has parenthesis), This string b (has parenthesis too), This string C hasn't."; 

NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:initialString attributes:defaultAttributes]; 
NSLog(@"Attr: %@", attr); 
NSArray *allMatches = [regex matchesInString:[attr string] options:0 range:NSMakeRange(0, [attr length])]; 
for (NSTextCheckingResult *aResult in allMatches) 
{ 
    [attr addAttributes:otherAttributes range:[aResult range]]; 
} 
NSLog(@"Attr: %@", attr); 

日誌:

$> Attr: This string a (has parenthesis), This string b (has parenthesis too), This string C hasn't.{ 
    NSFont = "<UICTFont: 0x14663df0> font-family: \".SFUIText-Semibold\"; font-weight: bold; font-style: normal; font-size: 15.00pt"; 
} 
$> Attr: This string a { 
    NSFont = "<UICTFont: 0x14663df0> font-family: \".SFUIText-Semibold\"; font-weight: bold; font-style: normal; font-size: 15.00pt"; 
}(has parenthesis){ 
    NSFont = "<UICTFont: 0x14666260> font-family: \".SFUIText\"; font-weight: normal; font-style: normal; font-size: 12.00pt"; 
}, This string b { 
    NSFont = "<UICTFont: 0x14663df0> font-family: \".SFUIText-Semibold\"; font-weight: bold; font-style: normal; font-size: 15.00pt"; 
}(has parenthesis too){ 
    NSFont = "<UICTFont: 0x14666260> font-family: \".SFUIText\"; font-weight: normal; font-style: normal; font-size: 12.00pt"; 
}, This string C hasn't.{ 
    NSFont = "<UICTFont: 0x14663df0> font-family: \".SFUIText-Semibold\"; font-weight: bold; font-style: normal; font-size: 15.00pt"; 
} 

是什麼概念:
與 「默認」 屬性(在我們的 「大尺寸」 的情況下加粗字體)創建NSMutableAttributedString
然後創建一個NSRegularExpression並查找所有匹配項。
您將在該出現範圍添加屬性(在我們的例子中是小字體和普通字體)。

在我們的案例中,它的工作原理很簡單,因爲由於每個種類最多隻能有一個屬性在特定範圍內,所以NSFontAttributeName屬性將被替換爲該範圍。

如果添加了更多的屬性,並希望刪除它們,則可能無需調用addAttributes:range:,但replaceCharactersInRange:withAttributedString:代替:

NSAttributedString *replacement = [[NSAttributedString alloc] initWithString:[[attr string] substringWithRange:[aResult range]] 
                    attributes:otherAttributes]; 
[attr replaceCharactersInRange:[aResult range] withAttributedString:replacement]; 

編輯:斯威夫特3版

諾塔Bene的:我顯然不是一個Swift開發者,這段代碼似乎有用,但很明顯,我寫「Swift」就像編寫Objective-C一樣,還有很多事情,因爲我沒有每天使用它們,也沒有閱讀過doc錯誤地完成(如轉換/ cast/explicit t ype/class,「as」,「!」,「?」等),但它可能是您的開始。 如果您是Swift開發人員和景點問題,請隨時對帖子發表評論並提出您的修改建議。如果你只是在這裏,因爲你有同樣的問題,不要忘記閱讀評論,如果有更多的Swifty的東西來解決我的僞代碼。

let defaultAttributes:[String:Any] = [NSFontAttributeName:UIFont.boldSystemFont(ofSize:15)]; 
let otherAttributes:[String:Any] = [NSFontAttributeName:UIFont.systemFont(ofSize:12)]; 


do { 
    let regex = try NSRegularExpression.init(pattern: "\\(.*?\\)", options: []) 
    let initialString:String = "This string a (has parenthesis), This string b (has parenthesis too), This string C hasn't." 
    let attr = NSMutableAttributedString.init(string: initialString, attributes: defaultAttributes) 
    print("Attr\(attr)"); 
    let allMatches:[NSTextCheckingResult] = regex.matches(in: attr.string, options:[], range: NSRange(location: 0, length: attr.string.characters.count)) 
    for aResult in allMatches 
    { 
     let occurrence = (attr.string as NSString).substring(with: aResult.range) 
     let replacement = NSAttributedString.init(string: occurrence , attributes: otherAttributes) 
     attr.replaceCharacters(in: aResult.range, with: replacement) 
    //attr.addAttributes(otherAttributes, range: aResult.range) 
    } 
    print("Attr\(attr)"); 
} catch let regexError { 
    print(regexError) 
} 
+0

感謝您的時間!我一直能夠跟隨,轉換到斯威夫特,但仍然掙扎着解決所有的錯誤。我會在接下來的日子裏一次又一次地檢查它,看看我能否得到它的工作。 – Simon

+0

@Simon我在Swift中編寫了一個僞代碼(它編譯和工作),我確信一些錯誤/壞習慣,但它可能會給你一個更好的主意。 – Larme

+0

超強大,並試圖讓它工作每一個免費的分鐘可用。這只是我對iOS和一般實際編碼的超級新手,所以有時候需要一些頭撞牆。 – Simon

相關問題