【问题标题】:Subclassing and overriding UITextField in Monotouch在 Monotouch 中继承和覆盖 UITextField
【发布时间】:2012-10-02 02:40:54
【问题描述】:

我正在尝试将 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);}
    }
}

【问题讨论】:

  • 这个问题已经回答正确。请参阅下面的 poupou 代码并关注评论跟踪以获取详细信息。

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


【解决方案1】:

原始的 ObjC 代码没有调用 super(它是基本方法),而是调用了 drawInRect:。你用 MonoTouch 尝试过同样的方法吗?例如

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 上调用)。

【讨论】:

  • 谢谢。我会试试这个,让你知道。您解决了我认为缺失的难题,即我不确定 drawInRect:WithFont: 映射到什么。现在我知道了,我会试一试。
  • 我试过这个。我可以让我的代码运行。实例化控件时,断点被击中。问题是它什么也没做。无论我做什么,控件都不会更新。占位符文本未显示。我尝试更改控件的背景颜色,代码被命中,但 UI 中没有任何变化.....嗯,有什么想法吗?在 XCode 中,我将 Class 设置为我的自定义类。所以那里没问题(加上断点被击中)。
  • 我将您提供的 ObjC 代码翻译成 C#,但我没有尝试(不是在 ObjC/Xcode 或 C#/MonoTouch 中)。但是,从原始链接来看,似乎并不适合所有人。如果您在 ObjC 中有一个工作示例,请提交错误报告 bugzilla.xamarin.com 并将其与您的 C# 端口一起包含在内,我们将对其进行查看。
  • 我找不到 String 的 DrawString 扩展方法。也许我错过了导入,但我在 .NET 文档中看不到关于 DrawString 是字符串的扩展方法的任何地方。当然,它是图形对象的扩展方法 - 哪个字符串不是。你确定 DrawString 吗?
  • 现在一切正常!我不得不将您对 DrawString 的调用更改为从 base 调用。非常感谢你的帮助。我将通过修改您所做的 DrawString 调用来修改您的条目。 public override void DrawPlaceholder (RectangleF rect) { using (UIFont font = UIFont.SystemFontOfSize (16)) using (UIColor col = new UIColor (0,0,255,(float)0.7)) { col.SetFill (); base.DrawString (base.Placeholder,rect, font); } }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-12
  • 1970-01-01
  • 2019-06-29
  • 2017-09-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多