Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
UITextField category and UIAppearance extensions
using Foundation;
using ObjCRuntime;
using UIKit;
namespace Categories
{
[Category(typeof(UITextField)), Preserve]
public static class UITextFieldPlaceholderTextColorExtensions
{
[Export("placeholderTextColor")]
public static UIColor PlaceholderTextColor(this UITextField self) =>
self.AttributedPlaceholder.GetAttribute(UIStringAttributeKey.ForegroundColor, 0, out _) as UIColor;
[Export("setPlaceholderTextColor:")]
public static void SetPlaceholderTextColor(this UITextField self, UIColor placeholderTextColor)
{
if (self.AttributedPlaceholder is null)
{
if (self.Placeholder is null)
{
return;
}
self.AttributedPlaceholder = new NSAttributedString(self.Placeholder,
new NSDictionary(UIStringAttributeKey.ForegroundColor, placeholderTextColor));
}
else
{
var attributedString = new NSMutableAttributedString(self.AttributedPlaceholder);
if (placeholderTextColor is null)
{
attributedString.RemoveAttribute(UIStringAttributeKey.ForegroundColor,
new NSRange(0, self.AttributedPlaceholder.Length));
}
else
{
attributedString.SetAttributes(
new NSDictionary(UIStringAttributeKey.ForegroundColor, placeholderTextColor),
new NSRange(0, self.AttributedPlaceholder.Length));
}
self.AttributedPlaceholder = attributedString;
}
}
private static readonly Selector PlaceholderTextColorSetter = new Selector("setPlaceholderTextColor:");
private static readonly Selector PlaceholderTextColorGetter = new Selector("placeholderTextColor");
public static void SetPlaceholderTextColor(this UITextField.UITextFieldAppearance self,
UIColor placeholderTextColor)
{
self.PerformSelector(PlaceholderTextColorSetter, placeholderTextColor);
}
public static UIColor GetPlaceholderTextColor(this UITextField.UITextFieldAppearance self)
{
var color = self.PerformSelector(PlaceholderTextColorGetter);
return (UIColor) color;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.