第一步:
self.naviView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_Width, 64)];
self.naviView.backgroundColor = [UIColor clearColor];
[self.view addSubview:self.naviView];
[self.view bringSubviewToFront:self.naviView];
[self setupSubViews];
第二步:
- (void)setupSubViews{
CGFloat searchViewWidth = Screen_Width/3 *2;
//搜索背景
self.searchView = [[UIView alloc] initWithFrame:CGRectMake(10, 22, searchViewWidth, 35)];
self.searchView.layer.cornerRadius = 15;
self.searchView.layer.masksToBounds = YES;
self.searchView.backgroundColor = [UIColor whiteColor];
[self.naviView addSubview:self.searchView];
self.mySearchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, searchViewWidth, 35)];
self.mySearchBar.placeholder = @"请输入搜索关键词";
self.mySearchBar.barTintColor = [UIColor whiteColor];
self.mySearchBar.layer.borderWidth = 1;
self.mySearchBar.layer.borderColor = [UIColor whiteColor].CGColor;
self.mySearchBar.layer.cornerRadius = 15;
self.mySearchBar.layer.masksToBounds = YES;
self.mySearchBar.backgroundColor = [UIColor clearColor];
UITextField * searchField = [self.mySearchBar valueForKey:@"_searchField"];
[searchField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[searchField setValue:[UIFont boldSystemFontOfSize:13] forKeyPath:@"_placeholderLabel.font"];
[self.searchView addSubview:self.mySearchBar];
//设置透明度
self.searchView.alpha = 0.8;
}
第三步:
#pragma mark - scrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGFloat alpha = scrollView.contentOffset.y / 100;
if (alpha>1) {
self.naviView.backgroundColor = [UIColor blueColor];
self.searchView.backgroundColor = [UIColor whiteColor];
self.searchView.layer.cornerRadius = 15.0f;
}else{
self.naviView.backgroundColor = [UIColor clearColor];
self.searchView.backgroundColor = [UIColor whiteColor];
self.searchView.layer.cornerRadius = 15.0f;
}
}