在Monotouch中对UITextField进行子类化和重写

时间:2012-10-02 02:40:55

标签: c# objective-c ios xamarin.ios uitextfield

我正在尝试将UITextField的占位符文本设置为其他颜色。我了解到我需要子类化并覆盖drawPlaceholderInRect方法。

iPhone UITextField - Change placeholder text color

    (void) drawPlaceholderInRect:(CGRect)rect {
    [[UIColor blueColor] setFill];
    [[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:16]];
}

这是我到目前为止所做的,但我无法弄清楚如何才能做到恰到好处。我在最后一行感到困惑,因为我不知道如何将它映射到MonoTouch / C#对象。

using System;
using MonoTouch.UIKit;
using MonoTouch.Foundation;
using System.Drawing;

namespace MyApp
{
    [Register("CustomUITextField")]
    public class CustomUITextField:UITextField
    {
        public CustomUITextField () :base()
        {

        }

        public CustomUITextField (IntPtr handle) :base(handle)
    {

    }    

        public override void DrawPlaceholder (RectangleF rect)
        {       

            UIColor col = new UIColor(0,0,255.0,0.7);
            col.SetFill();
            //Not sure what to put here
            base.DrawPlaceholder (rect);}
    }
}

1 个答案:

答案 0 :(得分:2)

原始的ObjC代码不会调用super(它的基本方法),而是drawInRect:。您是否尝试过使用MonoTouch? e.g。

public override void DrawPlaceholder (RectangleF rect)
{
    using (UIFont font = UIFont.SystemFontOfSize (16))
    using (UIColor col = new UIColor (0,0,255.0,0.7)) {
        col.SetFill ();
        base.DrawString (rect, font);
    }
}

注意:drawInRect:WithFont:映射到C#中的DrawString扩展方法(可以在任何string上调用)。