Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kipters/c5c7087954e406e3530237747fd2b67a to your computer and use it in GitHub Desktop.
Save kipters/c5c7087954e406e3530237747fd2b67a to your computer and use it in GitHub Desktop.
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