Is there a way to set cornerRadius
for only top-left and top-right corner of a UIView
?
I tried the following, but it end up not seeing the view anymore.
UIView *view = [[UIView alloc] initWithFrame:frame];
CALayer *layer = [CALayer layer];
UIBezierPath *shadowPath = [UIBezierPath bezierPathWithRoundedRect:frame byRoundingCorners:(UIRectCornerTopLeft|UIRectCornerTopRight) cornerRadii:CGSizeMake(3.0, 3.0)];
layer.shadowPath = shadowPath.CGPath;
view.layer.mask = layer;
This is how you can set a corner radius for each corner of a button with Xamarin in C#:
I am not sure why your solution did not work but the following code is working for me. Create a bezier mask and apply it to your view. In my code below I was rounding the bottom corners of the
_backgroundView
with a radius of 3 pixels.self
is a customUITableViewCell
:Swift version with some improvements:
Swift 3.0 version:
Swift extension here
In swift 4.1 and Xcode 9.4.1 onwards this code is enough
But for lower versions
If you are using AutoResizing in storyboard write this in viewDidLayoutSubviews
Emma:
.TopRight
and.BottomRight
are not working for you perhaps because the call toview.roundCorners
is done BEFORE finalview bounds
are calculated. Note that theBezier Path
derives from the view bounds at the time it is called. For example, if auto layout will narrow the view, the round corners on the right side might be outside the view. Try to call it inviewDidLayoutSubviews
, where the view's bound is final.All of the answers already given are really good and valid (especially Yunus idea of using the
mask
property).However I needed something a little more complex because my layer could often change sizes which mean I needed to call that masking logic every time and this was a little bit annoying.
I used swift
extensions
and computed properties to build a realcornerRadii
property which takes care of auto updating the mask when layer is layed out.This was achieved using Peter Steinberg great Aspects library for swizzling.
Full code is here:
I wrote a simple blog post explaining this.
Swift 4 Easy Way in 1 line