To a UIScrollView *toScrollView
(which is the width of the screen), I want to add a gray bottom border (exactly like that of the to-field of the compose view of the iPhone's native Messages app).
To achieve this, I followed Cocoa Touch: How To Change UIView's Border Color And Thickness? and just covered the top border with the custom UINavigationBar
and made the toScrollView
's x-coordinate -1 & width 322 so that the left & right borders are just off screen.
This looks fine, but it's sort of a hack, and I was wondering if there's a better way to do this.
- (void)viewDidLoad {
[super viewDidLoad];
// Add UINavigationBar *navigationBar at top.
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
target:self action:@selector(cancelAction)];
UINavigationBar *navigationBar = [[UINavigationBar alloc]
initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 44.0f)];
navigationBar.items = [NSArray arrayWithObject:self.navigationItem];
// Add UIScrollView *toScrollView below navigationBar.
UIScrollView *toScrollView = [[UIScrollView alloc]
initWithFrame:CGRectMake(-1.0f, 43.0f, 322.0f, 45.0f)];
toScrollView.backgroundColor = [UIColor whiteColor];
toScrollView.layer.borderColor = [UIColor colorWithWhite:0.8f alpha:1.0f].CGColor;
toScrollView.layer.borderWidth = 1.0f;
[self.view addSubview:toScrollView];
[self.view addSubview:navigationBar]; // covers top of toScrollView
}
You don't have to add a layer for each border, just use a bezier path to draw them once.
Instead of using a
UIView
, as @ImreKelényi suggests, you can use aCALayer
:The problem with these extension methods is that when the UIView/UIButton later adjusts it's size, you have no chance to change the CALayer's size to match the new size. Which will leave you with a misplaced border. I found it was better to subclass my UIButton, you could of course subclass other UIViews as well. Here is some code:
Or, the most performance-friendly way is to overload drawRect, simply like that:
If you use constraints (and so don't have the frame sizes) then you can add a border view with the required constraints
Then set it something like the below
(inspired by this answer)
Swift
Create UIView extension
Objective C
Create category class of UIView
UIView+Border.h
UIView+Border.m
Usage :- Select any control from storyboard, then show attribute inspector (Right side) You will see below image Example.(Note : Border only appear at run time.)
Now You can set any side of border colour and width.