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
}
Swift 4 extension with border width and color. Works great!
}
Implemented in a category as below:
UIButton+Border.h:
UIButton+Border.m:
I wrote a general method that will add a border on whichever sides you wish in any
UIView
. You can define thickness, color, margins andzOrder
for each side.You can add a separate
UIView
with 1 point height and gray background color toself.view
and position it right belowtoScrollView
.There is also improved code with remove border functionality. Based on confile answer.
Update: Swift 3
Swift 4/3
You can use this solution beneath. It works on UIBezierPaths which are lighter than layers, causing quick startup times. It is easy to use, see instructions beneath.