Xamarin Ios - Create rounded buttons on only 1 sid

2020-03-06 05:37发布

问题:

I'm currently developing an App for Xamarin Ios and i'm struggling to find a way to apply a rounded border to simply one side off a button of a UIButton type.

回答1:

In your UIButton subclass, override the LayoutSubviews method and add a mask:

Example: Top and bottom of left side rounded:

public override void LayoutSubviews()
{
    var maskingShapeLayer = new CAShapeLayer()
    {
        Path = UIBezierPath.FromRoundedRect(Bounds, UIRectCorner.BottomLeft | UIRectCorner.TopLeft, new CGSize(20, 20)).CGPath
    };
    Layer.Mask = maskingShapeLayer;
    base.LayoutSubviews();
}



回答2:

You can do this (IOS 11.0+):

yourLabel.Layer.CornerRadius = 5; // set radius on all corners
yourLabel.ClipsToBounds = true; 
yourLabel.Layer.MaskedCorners = (CoreAnimation.CACornerMask)1; // cast the correct value as CACornerMask enum

As CoreAnimation.CACornerMask is an enum marked as Flags and has only 4 values defined (1,2,4,8), I assumed that you can do bitwise operations there but that didn't work for me... So the only way is to cast it with a correct value like this:

yourLabel.Layer.MaskedCorners = (CoreAnimation.CACornerMask)5;  //top & bottom left corners rounded

Pick your value from this list based on which corners do you want to be rounded:

  • 0: no rounded corners
  • 1: top left
  • 2: top right
  • 3: top left & right (both top corners)
  • 4: bottom left
  • 5: top & bottom left (both left corners)
  • 6: top right & bottom left
  • 7: top left & right, bottom left (all corners except bottom right)
  • 8: bottom right
  • 9: top left, bottom right
  • 10: top & bottom right (both right corners)
  • 11: both top corners, bottom right (all corners except bottom left)
  • 12: bottom left & right (both bottom corners)
  • 13: bottom left & right, top left (all corners except top right)
  • 14: bottom left & right, top right (all corners except top left)
  • 15: all corners rounded

That does the trick...