2011-02-11 13 views
12

Próbuję utworzyć przypisany ciąg z przekreśleniem, jednak to proste zadanie wydaje się trudniejsze do wykrycia, niż się spodziewałem. Oto, co mam obecnie (co nie działa). Dzięki za pomoc!NSAttributedString z przekreśleniem

NSAttributedString *theTitle = [[[NSAttributedString alloc] initWithString:@"strikethrough text" attributes:[NSDictionary dictionaryWithObjectsAndKeys:[NSColor whiteColor], NSForegroundColorAttributeName, NSUnderlinePatternSolid, NSStrikethroughStyleAttributeName, nil]] autorelease]; 

Odpowiedz

18

pierwsze, wartość NSStrikethroughStyleAttributeName musi być NSNumber, a nie proste całkowitą. Po drugie, myślę, że trzeba to NSUnderlineStyleSingle:

...:[NSDictionary dictionaryWithObjectsAndKeys: 
     ..., 
     [NSNumber numberWithInteger:NSUnderlinePatternSolid | NSUnderlineStyleSingle], 
     NSStrikethroughStyleAttributeName, 
     nil]... 
+0

Działa doskonale ... dzięki. – ambientdiscourse

+0

To było bardzo pomocne. Dzięki! Warto zauważyć, że brakuje ci nawiasu zamykającego, aby zamknąć komunikat 'numberWithInteger:' po 'NSUnderlinePatternSolid | NSUnderlineStyleSingle' i before ', NSStrikethroughStyleAttributeName'. – morgant

15

Można też po prostu użyć:

NSAttributedString *theAttributedString; 
theAttributedString = [[NSAttributedString alloc] initWithString:theString 
      attributes:@{NSStrikethroughStyleAttributeName: 
      [NSNumber numberWithInteger:NSUnderlineStyleSingle]}]; 

Aktualizacja:

Swift 2.0 wersja

let theAttributedString = NSAttributedString(string: theString, attributes: [NSStrikethroughColorAttributeName: NSUnderlineStyle.StyleSingle]) 
+1

To jest złe, nie można przypisać stylu do atrybutu koloru. '[NSStrikethroughColorAttributeName: NSUnderlineStyle.StyleSingle]' –

2
func addAttributes(attrs: [String : AnyObject], range: NSRange) 

NSUnderlineStyleAttributeName: Wartością tego atrybutu jest obiekt NSNumber zawierający liczbę całkowitą.

Ponieważ NSUnderlineStyle ENUM w RawValue jest typu int, należy zainicjować NSNumber obiekt z nim

Swift2.1:

attrStr.addAttributes([NSStrikethroughStyleAttributeName: NSNumber(integer: NSUnderlineStyle.StyleSingle.rawValue)], range: NSMakeRange(x, y)) 

x jest lokalizacja, początek tekstu

y jest długością tekstu

+0

Zakres nie działa, gdy piszę 'NSRangeMake (0, 4)' który nie działa, jeśli piszę 'NSRangeMake (0, theAttributedString.lenght)' który działa, ale mój requirment to put horizontal line on only Pierwsze cztery znaki na łańcuchu, jak mogę to zrobić? – Dhiru

+0

W systemie iOS 10.3 występuje znany błąd, w którym atrybut strike through nie zadziała, jeśli zostanie zastosowany w zakresie. Aby obejść ten problem, wykonaj następujące czynności: 'attrStr.addAttributes ([NSBaselineOffsetAttributeName: NSNumber (integerLiteral: 0)], zakres: NSMakeRange (x, y))' – jdev

Powiązane problemy