Search code examples
iosswift2nsattributedstringswift3

Get foreground color of UITextField.placeHolder property?


I'm trying to get the foreground color of a UITextField.placeHolder object. I have to use one of the following members of the NSAttributeString:

attributesAtIndex(_:effectiveRange:)
attributesAtIndex(_:longestEffectiveRange:inRange:)
attribute(_:atIndex:effectiveRange:)
attribute(_:atIndex:longestEffectiveRange:inRange:)

There are a million examples on how to set attributes of an NSAttributeString,

uiTextFieldObject.attributedPlaceholder = 
   NSAttributedString(string:"placeholder text", attributes[NSForegroundColorAttributeName: UIColor.redColor()])

But I cannot find a simple example that retrieves a NSAttributeString attribute value. Any help would be greatly appreciated.


Solution

  • Try this - Place add validations

    Swift

    let attributedString = NSAttributedString(string: "Temp String",
                                                  attributes: [NSForegroundColorAttributeName: UIColor.redColor()])
    
        attributedString.enumerateAttribute(NSForegroundColorAttributeName,
                                            inRange: NSRange(location: 0, length: attributedString.length), options:NSAttributedStringEnumerationOptions(rawValue: 0)){(attribute, range, other) in
    
            if let color = attribute as? UIColor {
                print("color \(color)")
            }
        }
    

    Objective-C

    NSAttributedString * attributedString = [[NSAttributedString alloc]
                                       initWithString:@"Temp String"
                                       attributes:@{NSForegroundColorAttributeName:[UIColor redColor]}];
    
    [attributedString enumerateAttribute:NSForegroundColorAttributeName
                    inRange:NSMakeRange(0, attributedString.length)
                    options:0 usingBlock:^(id value, NSRange range, BOOL *stop) {
        if (value) {
            UIColor *color = (UIColor *)value;
            NSLog(@"Color : %@", color);
        }
    }];