[_firstPrincipleButton setBackgroundImage:[UIImage imageNamed:#"i_press.png"]
forState:UIControlStateNormal];
The above code is working fine in iOS7 but in iOS7.1 this is not changing the image of UIButton. I have also tried to do this with setImage but didn't work.
Thanks
Just in case that others have the same problem and need another hint on how to fix this:
I also had this problem and finally found out that setting a button's (background) image doesn't work on iOS 7.1, if the button is disabled.
Not sure if this fixes your problem, but it was mine. Calling setNeedsLayout didn't help in my case, unfortunately. What you can do as a workaround is either to override UIButton or to add a category that contains a method like the following to set an image:
- (void)setImage:(UIImage *)img forButtonState:(UIControlState)state
{
BOOL shouldEnable = self.enabled;
self.enabled = YES;
[self setImage:img forState:state];
self.enabled = shouldEnable;
}
Filed a bug report for this issue (16497031).
It is a bug in iOS 7.1 ,
you can create a category for UIButton and implement a method to set the image somewhat like this.
-(void)setImage:(UIImage *)image forButtonState:(UIControlState)state
{
CGFloat version = [[UIDevice currentDevice] systemVersion].floatValue ;
if( version <= 7.1)
{
BOOL isFirstTime = YES ;
for(UIView *aView in self.subviews)
{
if([aView isKindOfClass:[UIImageView class]])
{
[(UIImageView *)aView setImage:image] ;
isFirstTime = NO ;
break ;
}
}
if(isFirstTime)
{
CGRect frame = self.frame ;
frame.size = image.size ;
UIImageView * imageView = [[UIImageView alloc] initWithFrame:frame];
[imageView setImage:image];
[self addSubview:imageView];
}
}
else
[self setImage:image forState:state];
}
This will work.
enjoy coding :)
Related
So I'm having issues with the buttons for the filters in my photo app. I'm not exactly sure why, but they've suddenly stopped working. The selector is not being called when they're tapped, but I have no idea why. They were working just fine a few days ago, but for some reason they're not now. I've checked the UIView subviews array, verified that it's right on top. I need a way to see if, for some reason, the touches are not making it to the button. I'm not sure how to do this.
I wish I had more information to give, but this is all I've got. I hope someone has some suggestions because I'm at wit's end with it.
Thanks in advance!
Button Creation Method:
-(void)createFilterButtonsForThumbnail:(UIImage *)thumbnail
{
UIView *filtersContainer = self.filterContainer;
CGRect buttonFrame = CGRectMake(kFilterFrameThickness, kFilterFrameThickness,
thumbnail.size.width, thumbnail.size.height);
CGFloat frameWidth = thumbnail.size.width+(2*kFilterFrameThickness);
CGFloat frameHeight = kFilterPickerHeight;
UIEdgeInsets backgroundInsets = UIEdgeInsetsMake(0, kFilterFrameThickness, 0, kFilterFrameThickness);
UIImage *buttonBackgroundImage = [[UIImage imageNamed:#"FilmReel"] resizableImageWithCapInsets:backgroundInsets];
for (int i = 0;i<(self.filterPaths.count+kFilterNonLookups+1);i++){
UIImageView *buttonBackground = [[UIImageView alloc] initWithFrame:CGRectMake(kFilterSidePadding+(i*(frameWidth+kFilterSidePadding)),
0,
frameWidth,
frameHeight)];
[buttonBackground setImage:buttonBackgroundImage];
UIButton *thumbnailButton = [[UIButton alloc] initWithFrame:buttonFrame];
UIImage *filteredThumbnail = [self applyFilterAtIndex:i ToImage:thumbnail];
[thumbnailButton setImage:filteredThumbnail forState:UIControlStateNormal];
[thumbnailButton addTarget:self action:#selector(filterSelected:) forControlEvents:UIControlEventTouchUpInside];
[thumbnailButton setTag:i];
[buttonBackground addSubview:thumbnailButton];
[filtersContainer addSubview:buttonBackground];
if ((i > (kFilterProMinimumIndex)) && ([self isProVersion]) == NO){
UIImageView *proTag = [[UIImageView alloc] initWithImage:nil];
CGRect proFrame = CGRectMake(buttonFrame.origin.x,
buttonFrame.origin.y + buttonFrame.size.height - kFilterProIconHeight-kFilterFrameThickness,
kFilterProIconWidth,
kFilterProIconHeight);
[proTag setBackgroundColor:[UIColor orangeColor]];
[proTag setFrame:proFrame];
[thumbnailButton addSubview:proTag];
[self.filterProTags addObject:proTag];
}
}
}
Selector Method:
-(void)filterSelected:(UIButton *)button
{
NSLog(#"Pressed button for index %i",button.tag);
int buttonTag = button.tag;
if ((buttonTag < kFilterProMinimumIndex+1) || ([self isProVersion] == YES)){
[self.imageView setImage:[self applyFilterAtIndex:buttonTag ToImage:self.workingImage]];
}
else {
[self processProPurchaseAfterAlert];
}
}
I see a couple issues in this, but I'm not sure which ones are causing it to break. First, you should instantiate your button using buttonWithType: on UIButton:
UIButton *thumbnailButton = [UIButton buttonWithType:UIButtonTypeCustom];
[thumbnailButton setFrame:buttonFrame]
The reason for this is UIButton is a class cluster, and you should let the OS give you the correct button.
Secondly, you're adding the Button as a Subview of an UIImageView, which by default, has userInteractionEnabled set to NO.
This property is inherited from the UIView parent class. This class
changes the default value of this property to NO.
You should have the button be one large button, with the background of the button be the image you want it to be.
So I have an iOS7 app that I'm using a MPVolumeView in so the user can control the volume level. I have the route button hidden on this particular MPVolumeView and use another MPVolumeView with the slider disabled as my AirPlay icon.
My app supports both Portrait and landscape orientations, and the volume slider is a different width in these two different modes.
If the view gets initialized in Landscape mode first, then the MPVolumeView will resize itself correctly.
However, when the view gets initialized in Portrait mode and then I rotate to Landscape mode, EVERYTHING else in the app gets resized/moved except the MPVolumeView only gets moved, and it doesn't get shorter like it should.
I am using custom images on the MPVolumeView, and if I remove the custom images for the track, this problem goes away.
Here is the code used to initialize the MPVolumeView
self.volumeView = [[MPVolumeView alloc] initWithFrame:CGRectZero];
self.volumeView.showsRouteButton = NO;
self.volumeView.layer.borderColor = [[UIColor redColor] CGColor];
self.volumeView.layer.borderWidth = 1.0f;
if (AT_LEAST_IOS7) {
// TODO: BUGBUG iOS7 doesn't redraw this MPVolumeView correctly when it's frame changes (i.e. we rotate to the portrait view).
// These images simply make the bar a little thicker than the standard thickness (to match the iOS7 music app) but it's not redrawing
// correctly so we are going to have to live with a slightly thinner bar.
[self.volumeView setMaximumVolumeSliderImage:[UIImage imageNamed:#"volume_bar_max"] forState:UIControlStateNormal];
[self.volumeView setMinimumVolumeSliderImage:[UIImage imageNamed:#"volume_bar_min"] forState:UIControlStateNormal];
[self.volumeView setVolumeThumbImage:[UIImage imageNamed:#"volume_scrubber"] forState:UIControlStateNormal];
}
[self addSubview:self.volumeView];
And in layoutSubviews I am repositioning/scaling it's frame:
self.volumeView.frame = CGRectIntegral(CGRectMake(controlsLeft + kEdgeToSliderSideWidth,
volumeTop,
controlsWidth - (2 * kEdgeToSliderSideWidth),
volumeSize.height));
Here is what it looks like when the view starts out in Portrait Mode: (overall width of 640 pixels)
And when it gets rotated to Landscape it ends up looking like this: (overall width of 568 pixels)
Does anybody have any ideas?
I'm experiencing the same issue. My current workaround is to destroy and re-add the slider after a screen rotation:
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
//remove the old view
for (UIView *subview in self.volumeViewContainer.subviews)
[subview removeFromSuperview];
//recreate it
UIImage *slider = [[UIImage imageNamed:#"slider"] resizableImageWithCapInsets:UIEdgeInsetsMake(0.0, 15.0, 0.0, 15.0)];
UIImage *knobImage = [UIImage imageNamed:#"slider_knob"];
MPVolumeView *volumeView = [[[MPVolumeView alloc] initWithFrame:self.volumeViewContainer.bounds] autorelease];
[volumeView setMinimumVolumeSliderImage:slider forState:UIControlStateNormal];
[volumeView setMaximumVolumeSliderImage:slider forState:UIControlStateNormal];
[volumeView setVolumeThumbImage:knobImage forState:UIControlStateNormal];
[self.volumeViewContainer addSubview:volumeView];
}
Doing that there is still the issue that the slider is still displayed with glitches DURING rotation. That's why I render the slider to an image and swap the slider with said image before a rotation takes place:
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
//render to UIImage
UIGraphicsBeginImageContextWithOptions(self.volumeViewContainer.frame.size, NO, 0.0);
[self.volumeViewContainer.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//remove old slider
for (UIView *subview in self.volumeViewContainer.subviews)
[subview removeFromSuperview];
//add UIImageView which resizes nicely with the container view
UIImageView *imageView = [[[UIImageView alloc] initWithFrame:self.volumeViewContainer.bounds] autorelease];
imageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
imageView.image = img;
[self.volumeViewContainer addSubview:imageView];
}
I know that this is not a real solution, but I think it's better than nothing and I hope it helps you.
After doing a lot of experimentation, it seems that MPVolumeView is very buggy in iOS 7.0.x.
I was having an issue where having custom images for min/max sliders, volume thumb and route would sometimes cause the slider to expand to cover the route button.
When I changed the order in which these are invoked, it fixed the issue. The trick is to call setVolumeThumbImage and setRouteButtonImage first, then setMinimumVolumeSliderImage and setMaximumVolumeSliderImage.
That took care of the overlapping track over the route button.
HOWEVER, this caused a new issue, wherein the maximumSliderImage began overlapping the volumeThumbImage!
The final solution was to bring the thumb layer to front as follows, in a subclass of MPVolumeView:
- (void)_initialize {
UIImage *scrubber = [UIImage imageNamed:#"volume_scrubber_grip"];
scrubberSize = scrubber.size;
[self setVolumeThumbImage:scrubber forState:UIControlStateNormal];
[self setRouteButtonImage:[UIImage imageNamed:#"airplay_button"] forState:UIControlStateNormal];
[self setMinimumVolumeSliderImage:[UIImage imageNamed:#"min_slider"] forState:UIControlStateNormal];
[self setMaximumVolumeSliderImage:[UIImage imageNamed:#"max_slider"] forState:UIControlStateNormal];
}
- (void)layoutSubviews {
[super layoutSubviews];
[self.subviews enumerateObjectsUsingBlock:^(UIView *obj, NSUInteger idx, BOOL *stop) {
if([obj isKindOfClass:[UISlider class]]) {
UISlider *slider = (UISlider *)obj;
[slider.subviews enumerateObjectsUsingBlock:^(UIView *obj2, NSUInteger idx, BOOL *stop2) {
if(CGSizeEqualToSize(obj2.frame.size, scrubberSize)) {
[obj bringSubviewToFront:obj2];
*stop2 = YES;
}
}];
*stop = YES;
}
}];
}
I tested another solution that works fine. I embed the MPVolumeView in a simple UIView (that can be created in the storyboard). Then I do key-value observing on the property "bounds" of the UIView. When this property changes, I update MPVolumeView's frame to the new bounds of the UIView.
This solution handles both, autorotation and autolayout.
import UIKit
import MediaPlayerclass ViewController: UIViewController {
#IBOutlet weak var volumeViewContainer: UIView!
override func viewDidLoad() {
super.viewDidLoad()
volumeViewContainer.backgroundColor = UIColor.grayColor()
var volumeView = MPVolumeView(frame: volumeViewContainer.bounds)
volumeViewContainer.addSubview(volumeView)
volumeViewContainer.addObserver(self, forKeyPath: "bounds", options: nil, context: nil)
}
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
if let subview = volumeViewContainer.subviews.first as? UIView {
subview.frame = volumeViewContainer.bounds
}
}
}
#IBOutlet var volumeViewHolder: UIView!
override func viewDidLoad() {
super.viewDidLoad()
volumeViewHolder.backgroundColor = UIColor.clearColor()
var volumeView : MPVolumeView = MPVolumeView()
volumeView.frame = volumeViewHolder.frame
volumeView.center = volumeViewHolder.center
volumeView.sizeToFit()
volumeView.showsRouteButton = false
volumeView.showsVolumeSlider = true
volumeView.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
volumeViewHolder.addSubview(volumeView)
}
I have a UIImageView that when a function called I want to change to a different ("active") image and when another called change back to the image before. This is the code:
- (NavButton *)initWithFrame:(CGRect *)fr andImage:(UIImage *)img andActiveImage:(UIImage *)acImg {
NavButton *a = [[NavButton alloc] initWithFrame:*fr];
[a setBackgroundColor:[UIColor clearColor]];
UIImageView *aImg = [[UIImageView alloc] initWithFrame:CGRectMake(8.5, 8.5, 28, 28)];
aImg.tag = 13;
aImg.image = img;
self.orginalImage = img;
self.activeImage = acImg;
[a addSubview:aImg];
return a;
}
- (void)setIsActive:(NSNumber *)isActive {
self.active = isActive;
if ([isActive isEqualToValue:[NSNumber numberWithBool:NO]]) {
[self undoActive];
} else {
[self redoActive];
}
}
- (void)undoActive {
UIImageView *a = (UIImageView *)[self viewWithTag:13];
a.image = self.orginalImage;
}
- (void)redoActive {
UIImageView *a = (UIImageView *)[self viewWithTag:13];
a.image = self.activeImage;
}
When I call [btn setIsActive:[NSNumber numberWithBool:YES]]; or [btn setIsActive:[NSNumber numberWithBool:NO]]; both times it removes the image, but when I don't call either the image stays there. So, how do I make it so when I call them it changes the images of the button to the correct image?
Instead of repeatedly assigning image to imageview, you can assign two images to the image view: one to "image" property and other to "highlightedImage" property. When you want to switch between the images, set the Boolean property "highlighted" as YES or NO.
It will be easier just to do your check as:
if (![isActive boolValue]) {
Then, do some debugging, add some breakpoints and / or logging. Check what values are actually being received. Are the flags set correctly. Are the images set correctly. Is anything nil.
In my iPhone app i am getting around 300 images url from web server, i need to display all the images on UIScrollView in 3x3 row and column format. Once i get all the url from web server, convert them into UIImage and display image. Everything works fine, however after loading 200 images app crashes, I have read a lot its some thing memory kind of issue with UIScrollView, so how can we work on this. I have read apple documentation also, however its not clear.
here is the solution, i've implemented it in my app. Here is my code
sv_port is my scrollView.
Download SDWebImageDownloader class files and import it in your project. Add relevant framework in your project. like imageIO.framework, QuartzCore
Now, in your .m add
#import "UIImageView+WebCache.h"
#import "SDImageCache.h"
#import "SDWebImageCompat.h"
//function for adding image in your scrollview
-(void)populateImages
{
int x=6,y=6;
for(UIView * view in sv_port.subviews){
if([view isKindOfClass:[UIImageView class]])
{
[view removeFromSuperview]; view = nil;
}
if([view isKindOfClass:[UIButton class]])
{
[view removeFromSuperview]; view = nil;
}
}
for(int p=0;p<[Manufacturer count];p++)
{
UIButton *btnImageButton = [UIButton buttonWithType:UIButtonTypeCustom];
btnImageButton.frame = CGRectMake(x,y,70,70);
[btnImageButton setTag:p];
[btnImageButton addTarget:self action:#selector(nextview:) forControlEvents:UIControlEventTouchUpInside];
UIActivityIndicatorView *spinny = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
spinny.frame=CGRectMake(btnImageButton.frame.origin.x+25,btnImageButton.frame.origin.y+25, 20, 20);
spinny.backgroundColor=[UIColor clearColor];
[spinny startAnimating];
[sv_port setScrollEnabled:YES];
[sv_port addSubview:spinny];
UIImageView *asyncImageView = [[[UIImageView alloc] initWithFrame:btnImageButton.frame] autorelease];
asyncImageView.backgroundColor=[UIColor clearColor];
CALayer *layer;
layer = asyncImageView.layer;
layer.borderWidth = 0.5;
layer.cornerRadius = 5;
layer.masksToBounds = YES;
[asyncImageView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#", yourUrl] ] placeholderImage:[UIImage imageNamed:nil] options:0 andResize:CGSizeMake(btnImageButton.frame.size.width,btnImageButton.frame.size.height) withContentMode:UIViewContentModeScaleAspectFit];
asyncImageView.contentMode = UIViewContentModeScaleAspectFit;
[sv_port addSubview:btnImageButton];
[sv_port addSubview:asyncImageView];
int imgCntPort=0;
imgCntPort=(sv_port.frame.size.width/(asyncImageView.frame.size.width));
////NSLog(#"imgport %d",imgCntPort);
if((p+1)%imgCntPort==0)
{
x=5;
y=y+80;
}
else
{
x=x+80;
}
}
sv_port.contentSize = CGSizeMake(0, y);
glob_x =0; glob_y =y;
}
hope it helps..
-(void)scrollimage
{
[AsyncImageLoader sharedLoader].cache = nil;
NSArray *viewsToRemove = [_scrollview_gallary subviews];
for (UIView *v in viewsToRemove) {
[v removeFromSuperview];
}
CGFloat width =_scrollview_gallary.bounds.size.width;
_scrollview_gallary.contentSize=CGSizeMake(width*[tmpArr count]-1, 360);
[_scrollview_gallary setShowsHorizontalScrollIndicator:NO];
[_scrollview_gallary setShowsVerticalScrollIndicator:NO];
int x=0;
int y=0;
for (int i=0; i<[tmpArr count]; i++)
{
AsyncImageView *imgv;
imgv =[[AsyncImageView alloc] initWithFrame:CGRectMake(x,y,width,360)];
imgv.contentMode = UIViewContentModeScaleToFill;
imgv.activityIndicatorStyle = UIActivityIndicatorViewStyleWhite;
NSString *strimag=[NSString stringWithFormat:#"%#",[tmpArr objectAtIndex:i]];
imgv.imageURL=[NSURL URLWithString:[tmpArr objectAtIndex:i]];
[_scrollview_gallary addSubview:imgv];
x=x+width;
}
_pageview.numberOfPages=([tmpArr count]);
_scrollview_gallary.pagingEnabled = YES;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
int page;
CGFloat pageWidth = _scrollview_gallary.frame.size.width;
page = floor((_scrollview_gallary.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
self.pageview.currentPage = page;
}
I am getting an impression that you are downloading all 300 images together at once and keeping in memory and adding to the UIScrollView..
There is a technique called LazyLoad, means don't load all the images at once, load it in queue..
You can refer to this link http://lazyloadinginuiscrollviewiniphone.blogspot.in/2011/12/iphone-uiscrollview-lazy-image-loading.html it might help you to achieve things smoothly..
All the best.
If you want to display images in Gridview format then you can use PSTCollectionView. And for the lazy loading of the image you can use SDWebImage.
Are you releasing the elements that are not visible anymore? UITableView does that (that's why Sandro suggested it).
Your implementation of the UIScrollView should do that.
You can also consider UICollectionView or GMGridView for grid implementations that take this into consideration.
I do not see why what you're doing is a problem. May be you've got memory issue. In that case simulator and device result should be different.
If this is a memory problem, you should use a tableview instead of a scroll view. Put 3 images in each table view cell, and that should do the trick.
Cdt
This question already has answers here:
How to change inside background color of UISearchBar component on iOS
(26 answers)
Closed 7 years ago.
How can set the background image, or clear the background, of a search bar, like the note application?
A future-proof way:
[searchBar setBackgroundImage:[UIImage new]];
[searchBar setTranslucent:YES];
mj_ has the answer that i used. i was just going to comment as such but i can't yet. So i'll just post my own answer with my implementation where I add a search bar to the top of a table view with a semi-transparent BG.
DLog(#" Add search bar to table view");
//could be a UIImageView to display an image..?
bg = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 45)] autorelease];
bg.backgroundColor = [UIColor blackColor];
UISearchBar *sb = [[[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, 290, 45)] autorelease];
sb.barStyle = UIBarStyleBlackTranslucent;
sb.showsCancelButton = NO;
sb.autocorrectionType = UITextAutocorrectionTypeNo;
sb.autocapitalizationType = UITextAutocapitalizationTypeNone;
sb.delegate = self;
[bg addSubview:sb];
table.tableHeaderView = bg;
for (UIView *subview in sb.subviews) {
if ([subview isKindOfClass:NSClassFromString(#"UISearchBarBackground")]) {
[subview removeFromSuperview];
break;
}
}
I had problems w/ the answer above. I used the following.
for (UIView *subview in searchBar.subviews) {
if ([subview isKindOfClass:NSClassFromString(#"UISearchBarBackground")]) {
[subview removeFromSuperview];
break;
}
}
This worked for me (ios4.2+)
// Change the search bar background
-(void)viewWillAppear:(BOOL)animated {
for (UIView *subview in self.searchBar.subviews) {
if ([subview isKindOfClass:NSClassFromString(#"UISearchBarBackground")]) {
UIView *bg = [[UIView alloc] initWithFrame:subview.frame];
bg.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"search_bar_bg"]];
[self.searchBar insertSubview:bg aboveSubview:subview];
[subview removeFromSuperview];
break;
}
}
}
I just came up with a solution that works really well. You have to override the UISearchBar and then hide both the Background and Segment Control layers. Then Draw the background.
# .m
#import "UISearchBar.h"
#import <QuartzCore/QuartzCore.h>
#implementation UISearchBar(CustomBackground)
- (id)init
{
for ( UIView * subview in self.subviews )
{
if ([subview isKindOfClass:NSClassFromString(#"UISearchBarBackground") ] )
subview.alpha = 0.0;
if ([subview isKindOfClass:NSClassFromString(#"UISegmentedControl") ] )
subview.alpha = 0.0;
}
return self;
}
+ (UIImage *) bgImagePortrait
{
static UIImage *image = nil;
if (image == nil)
image = [[UIImage imageNamed:#"UISearchBarBack.png"] retain ];
return image;
}
+ (UIImage *) bgImageLandscape
{
static UIImage *image = nil;
if (image == nil)
image = [[UIImage imageNamed:#"UISearchBarBack.png"] retain];
return image;
}
- (void) drawLayer:(CALayer *)layer inContext:(CGContextRef)contenxt
{
if ([self isMemberOfClass:[UISearchBar class]] == NO)
return;
UIImage * image = ( self.frame.size.width > 320 ) ? [UISearchBar bgImageLandscape ] : [UISearchBar bgImagePortrait ];
for ( UIView * subview in self.subviews ) {
if ([subview isKindOfClass:NSClassFromString(#"UISearchBarBackground") ] )
subview.alpha = 0.0;
if ([subview isKindOfClass:NSClassFromString(#"UISegmentedControl") ] )
subview.alpha = 0.0;
}
CGContextTranslateCTM( contenxt , 0 , image.size.height );
CGContextScaleCTM( contenxt, 1.0, -1.0 );
CGContextDrawImage( contenxt , CGRectMake( 0 , 0 , image.size.width , image.size.height ), image.CGImage );
}
#end
# .h
#import <Foundation/Foundation.h>
#import <QuartzCore/QuartzCore.h>
#interface UISearchBar(CustomBackground)
#end
Hope this helps!
You have two questions here:
1.UISearchBar clear background color:
See my answer here
2.Set background image
Solution:(If you are in iOS 5.0 +)
[[UISearchBar appearance]setSearchFieldBackgroundImage:[navBarGradImage resizableImageWithCapInsets:inset2] forState:UIControlStateNormal];
NOTE: You can also try using a transparent image as a background.
Hope this helps.
I prefer to just set the alpha to 0 so you can hide/show on demand.
// Hide
[[self.theSearchBar.subviews objectAtIndex:0] setAlpha:0.0];
// Show
[[self.theSearchBar.subviews objectAtIndex:0] setAlpha:1.0];
How to set background color in UISearchBar:
#import <QuartzCore/QuartzCore.h>
Then make an outlet connection to search bar (say, objSearchbar), and use these lines :
for (UIView *subview in self.objSearchbar.subviews)
{
if ([subview isKindOfClass:NSClassFromString(#"UISearchBarBackground")])
{
[subview removeFromSuperview];
break;
}
}
self.tweetSearchbar.layer.backgroundColor = [UIColor blueColor].CGColor;
searchBar.searchBarStyle = UISearchBarStyleMinimal;
Look here: UISearchbar background image change
with iOS8 sdks apple moved #"UISearchBarBackground" view one level deeper, so have will need to look at subviews of the child-views as bellow,
for (UIView *subview in searchBar.subviews) {
for(UIView* grandSonView in subview.subviews){
if ([grandSonView isKindOfClass:NSClassFromString(#"UISearchBarBackground")]) {
grandSonView.alpha = 0.0f;
}else if([grandSonView isKindOfClass:NSClassFromString(#"UISearchBarTextField")] ){
NSLog(#"Keep textfiedld bkg color");
}else{
grandSonView.alpha = 0.0f;
}
}//for cacheViews
}//subviews
Set background image
UIImageView *backgroundView = [[UIImageView alloc] initWithFrame:searchBar.bounds];
backgroundView.image = [UIImage imageNamed:#"xxxx.png"];
[searchBar insertSubview:backgroundView atIndex:1]; // at index 1 but not 0
[backgroundView release];
One liner:
[[self.theSearchBar.subviews objectAtIndex:0] removeFromSuperview];