0

I'm trying to set a gradient using CAGradientLayer to a cell in StyledStringElement. This is the code I have so far:

public class DerreckStyledStringElement : StyledStringElement
{
    public DerreckStyledStringElement(string caption) : base(caption) {
    }

    public override UITableViewCell GetCell(UITableView tv)
    {
        var x = base.GetCell(tv);
        CAGradientLayer g = new CAGradientLayer();
        g.Frame = x.Frame;
        g.MasksToBounds = true;
        x.ClipsToBounds = true;
        g.Colors = new MonoTouch.CoreGraphics.CGColor[]
        {
            new UIColor(0f, 153f, 235f, 255f).CGColor,
            new UIColor(0f, 197f, 244f, 255f).CGColor
        };

        UIView bg = new UIView(x.Bounds);
        bg.TranslatesAutoresizingMaskIntoConstraints = true;
        bg.Layer.InsertSublayer(g, 0);
        x.BackgroundView = bg;

        this.TextColor = UIColor.White;
        return x;
    }

}

The button I'm testing this on, which sits by itself, looks like a square without the rounded corners and the right side extends to the right edge of the device. Most likely, it could be extending a little farther off the screen since the button has a left margin which looks correct.

What it should look like
|  /---------------------\  |
|  |    BUTTON TEXT      |  |
|  \---------------------/  |

What it looks like
|  |------------------------|
|  |    BUTTON TEXT         |
|  |------------------------|

The places where I used g.MasksToBounds = true;, x.ClipsToBounds = true;, and bg.TranslatesAutoresizingMaskIntoConstraints = true; were attempts at getting the background to clip to the button frame itself.

Since I haven't modified the SelectedBackground, when tapped it does show the correct rounded rectangle frame around it.

Also, the color looks right but the gradient looks stretched so the button looks like one color from the gradient rather than the gradient itself.

What am I doing wrong?

Derreck Dean
  • 3,708
  • 1
  • 26
  • 45

1 Answers1

0

Individual cells are responsible for rendering themselves with rounded corners.

There are several approaches, one is to do it during rendering (see ImageElement for an example). Another, if you choose to go down the layer path is to set the CornerRadius property on the layer.

miguel.de.icaza
  • 32,654
  • 6
  • 58
  • 76
  • Thanks, I'll check out ImageElement and see how it is done there. Besides that, is there any other way to do this without using images or using a layer? I see that I'm just adding a layer to the top and it's not respecting the boundaries of the button at all, and I felt the layer route probably was not the way to go here. – Derreck Dean Jun 05 '13 at 12:55