2

I would like to change the title of the cancel button of the UISearchBar using MonoTouch. Yes I have seen this "hack" but I prefer a more elegant way. I am trying to use:

UIButton.AppearanceWhenContainedIn(typeof(UISearchBar)).SetTitle("xxxx");

which it is supposed to work in objective-c but in MonoTouch I get the following error

message: Error CS1061: Type MonoTouch.UIKit.UIButton.UIButtonAppearance' does not contain a definition forSetTitle' and no extension method SetTitle' of type MonoTouch.UIKit.UIButton.UIButtonAppearance' could be found (are you missing a using directive or an assembly reference?)

I am using Xamarin Studio ver. 4.0

Community
  • 1
  • 1
vassilag
  • 450
  • 8
  • 18

3 Answers3

3

It's hackish - the Objective-C code works because the current implementation of UIAppearance use a proxy object. IOW Apple did not promise to keep the implementation identical and that specific feature is not documented.

Now that you're aware of this and if you still want to use it with Xamarin.iOS then you can do it using the hack I described in this Q&A. That will allow you to use any UIButton API on the UIAppearance proxy.

Community
  • 1
  • 1
poupou
  • 43,413
  • 6
  • 77
  • 174
2

Why not use a bit more lightweight hack?

    public static void SetSearchBarCancelButtonTitle (UISearchBar sb, string title)
    {
        foreach (var subview in sb.Subviews)
            if (subview is UIButton)
                (subview as UIButton).SetTitle (title, UIControlState.Normal);
    }
Maxim Korobov
  • 2,574
  • 1
  • 26
  • 44
0

UIButton no longer appears to be a direct subView of UISearchBar. You'll have to recurse like the following, until it is found:

        public static bool SetButton(UIView parentView, string title, UIColor tint)
        {
            foreach (var sub in parentView.Subviews)
            {
                if (sub is UIButton)
                {
                    (sub as UIButton).SetTitle(title, UIControlState.Normal);
                    (sub as UIButton).SetTitleColor(tint, UIControlState.Normal);
                    return true;
                }

                if (SetButton(sub, title, tint))
                    return true;
            }

            return false;
        }
ddebilt
  • 53
  • 1
  • 3