How do you change font in UISearchBar for iOS5? - iphone

I'm trying to change the font for all of my UISearchBar objects using the new "appearance" proxy for iOS5 with something like:
[[UISearchBar appearance] setTitleTextAttributes:
[NSDictionary dictionaryWithObjectsAndKeys:
[UIColor whiteColor], UITextAttributeTextColor,
[UIFont fontWithName:#"Trebuchet MS" size:0.0], UITextAttributeFont,
nil]];
Every time I run this, I'm getting this error:
"2012-05-28 03:01:52.264 DirectDx_ClientApp[30039:15503] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_UIAppearance setTitleTextAttributes:]: unrecognized selector sent to instance 0x8460cf0'
* First throw call stack:
(0x1ea8022 0x3a4fcd6 0x1ea9cbd 0x1e0eed0 0x1e0ecb2 0x5e695 0x5dd78 0x217aa 0x789386 0x78a274 0x799183 0x799c38 0x78d634 0x203bef5 0x1e7c195 0x1de0ff2 0x1ddf8da 0x1dded84 0x1ddec9b 0x789c65 0x78b626 0x2164d 0x2895 0x1)
terminate called throwing an exception"
The method above works perfectly well with UITabBar and UINavigationBar.
Any insights?
Thanks very much in advance.

Try this,It's Working Fine for iOS 5.0 and up (iOS 7 also):
- (void)viewDidLoad
{
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setFont:[UIFont fontWithName:#"Helvetica" size:20]];
}
For iOS 8
- (void)viewDidLoad
{
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setDefaultTextAttributes:#{
NSFontAttributeName: [UIFont fontWithName:#"Helvetica" size:20],
}];
}

Checkout the apple reference guide for uisearchbar, under customizing appearance you can see what methods are avialable to you for a uisearchbar. SetTitleAttributes is not possible for a uisearchbar and I can not see another method where you change the font of the uisearchbar by means of appearance.
Trying to call a method that is not supported by an object, will always give you an error. In your case setTitleArtributes is supported by other classes but sadly enough not for the uisearchbar.
There is a workaround.

Try using this code
UITextField *textField = [self.searchBar valueForKey: #"_searchField"];
[textField setFont:[UIFont fontWithName:#"HelveticaNeue-Light" size:17.0]];
Hope this will work for u.

Related

NSMutableAttributeString not working in iOS 10.0 in UIAlertController

Hello am using NSMutableAttributedString to show different fonts but with same size in UIAlertController, the problem here is it showing two different fonts which is correct but it also showing two different sizes.Here is my code
UIFont *regularFont = [UIFont fontWithName:#"HelveticaNeue" size:11.0];
UIFont *boldFont = [UIFont fontWithName:#"HelveticaNeue-Bold" size:11.0];
UIAlertController *alertObj = [UIAlertController alertControllerWithTitle:nil message:messageStr preferredStyle:UIAlertControllerStyleAlert];
NSMutableAttributedString *attMessage = [[NSMutableAttributedString alloc] initWithString:messageStr];
[attMessage addAttribute:NSFontAttributeName value:regularFont range:NSRangeFromString(messageStr)];
[attMessage addAttribute:NSFontAttributeName value:boldFont range:NSMakeRange(25, 6)];
[attMessage addAttribute:NSFontAttributeName value:boldFont range:NSMakeRange(35, 15)];
[alertObj setValue:attMessage forKey:#"attributedMessage"];
Result can be match.Any help would be appreciated
The attributedMessage property is not public, using it is a good way to get your app rejected at the review. If you really need to style the dialogue and distribute the app on the App Store, I think you should build your own component to display the pop-up.

IOS erro at Posting to Facebook with the native Share dialog - UICGColor encodeWithCoder

Erro:
Assertion failure in -[UICGColor encodeWithCoder:],
/SourceCache/UIKit/UIKit-2372/UIColor.m:1191 2012-11-15 14:17:45.531
Neemu Clothes[15179:4d07] Terminating app due to uncaught exception
'NSInternalInconsistencyException', reason: 'Only support RGBA or the
White color space, this method is a hack.'
* First throw call stack: (0x363272a3 0x32afe97f 0x3632715d 0x37a492af 0x36c793c5 0x379ec00f 0x379eb8b5 0x36dac72d 0x36daba7b
0x3632462f 0x36dab7f5 0x36e895e5 0x36e17cd7 0x36e17b6d 0x3506890f
0x36e17a61 0x36e210d5 0x3505b83b 0x36e210b1 0x3505b11f 0x3505a99b
0x3505a895 0x35069215 0x350693b9 0x357f8a11 0x357f88a4)
libc++abi.dylib: terminate called throwing an exception
Code:
BOOL displayedNativeDialog = [FBNativeDialogs presentShareDialogModallyFrom:self initialText:#"NeeemuG - Veja meu look." image:nil url:[NSURL URLWithString:#"https://www.neemu.com"] handler:^(FBNativeDialogResult result, NSError *error) {
// Only show the error if it is not due to the dialog
// not being supporte, i.e. code = 7, otherwise ignore
// because our fallback will show the share view controller.
if (error && [error code] == 7) {
return;
}
NSString *alertText = #"";
if (error) {
alertText = [NSString stringWithFormat:
#"error: domain = %#, code = %d",
error.domain, error.code];
} else if (result == FBNativeDialogResultSucceeded) {
alertText = #"Posted successfully.";
}
if (![alertText isEqualToString:#""]) {
// Show the result in an alert
[[[UIAlertView alloc] initWithTitle:#"Result"
message:alertText
delegate:self
cancelButtonTitle:#"OK!"
otherButtonTitles:nil]
show];
}
}];
// Fallback, show the view controller that will post using me/feed
if (!displayedNativeDialog) {
NSLog(#"No IOS6.");
}
In my delegate i put [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"background"]] to background navigation bar, i dont know why this crash, but when i remove resolve
the problem.
I had the same problem and it seems (obviously) linked with the method [UIColor colorWithPatternImage:image];
So, I suggest to check each method that call colorWithPatternImage and comment each line that call that method one by one to find out the source.
For my case, it was the colorWithPatternImage on the UIPageControl in my AppDelegate.
A lot of question is about this problem. Example : UIApperance and various crashes
or
iOS 6 MFMailComposeViewController: Only support RGBA or the White color space, this method is a hack
For me this error was caused by the appearance settings on UITextField and UISwitch.
I have an abstract view controller subclass, which all of my view controllers inherit from, so I just specified to only set the appearance in my views that inherit from this view controller.
Like so:
[[UITextField appearanceWhenContainedIn:[BaseViewController class], nil] setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"bkg"]]];
[[UISwitch appearanceWhenContainedIn:[BaseViewController class], nil] setOnTintColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"bkg"]]];
I had the same problems and I fixed that by subclassing components. My case was:
UIColor *bkg = [UIColor colorWithPatternImage:[UIImage imageNamed:#"bkg"]];
[[UICollectionView appearance] setBackgroundColor:bkg];
When I was trying to post something on facebook I received error, but then I created simple subclass of UICollectionView - let's name it MyGridView. So after modification my code was:
UIColor *bkg = [UIColor colorWithPatternImage:[UIImage imageNamed:#"bkg"]];
[[MyGridView appearance] setBackgroundColor:bkg];
Then I changed views in storyboards to use custom component class MyGridView instead of default UICollectionView and everything worked - I had background I wanted and was able to post on facebook.
I think if your problem is similar to mine you could try this approach and subclass components you need (if they are intended to be subclassed of course).
Best regards

EXC_BAD_ACCESS on UITextAttributeFont (Invalid iOS version)

I'm using setTitleTextAttributes to change the font on a UISegmentedControl as follows.
UIFont *font = [UIFont boldSystemFontOfSize:14.0f];
NSDictionary *attributes = [NSDictionary dictionaryWithObject:font forKey:UITextAttributeFont];
[self setTitleTextAttributes:attributes forState:UIControlStateNormal];</pre></code>
This works fine in the simulator, but crashed when running on an iPad. The bad access fault occurs on creation of the dictionary and I used an NSLog statement to verify that UITextAttributeFont is generating the fault.
Any ideas what the problem is here or if there is an alternative method to set the font?
EDITED
I just realized the iPad is running iOS 4 (I believe this is supported on iOS >= 5). What is the best way to test for version support?
Based on Dirty Henry's suggestion, the correct implementation is as follows.
if ([self respondsToSelector:#selector(setTitleTextAttributes: forState:)]) {
UIFont *font = [UIFont boldSystemFontOfSize:14.0f];
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys: font, UITextAttributeFont, nil];
[self setTitleTextAttributes:attributes forState:UIControlStateNormal];
}
Is your iPad running iOS 5.0 or later? (UITextAttributeFont has been introduced in this version). (i don't see anything wrong with your code either)

Incorrect decrement warning from Xcode from my class method

I created a class to take care of my UILabels in 1 line instead of taking 4-5 by doing...
+(UILabel*)BeautifyLabel:(UILabel *)label withText:(NSString *)message withFont:(NSString *)font andSize:(float)size andColor:(UIColor *)theColor{
label.backgroundColor = [UIColor clearColor];
label.textColor = theColor;
label.font = [UIFont fontWithName:font size:size];
label.text = message;
return label;
}
And to call it, i do
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake....];
label = [CommonMethods BeautifyLabel:label withText:#"hi" withFont:#"Helvetica" andSize:13 andColor:[UIColor whiteColor]];
[self.view addSubview label];
[label release];
The analyzer probably doesn't like the part where I pass the label to my CommomMethods class, but since i'm initializing and releases the label in the current controller and the CommonMethods class doesn't do anything memory related, this is safe, right?
Also, would this be cause for Apple to reject my app?
Thanks
Your BeautifyLabel method should not return the label pointer. That is probably what the analyzer is complaining about (but it would be nice to see the text of the analyzer error).
The analyzer is assuming that BeautifyLabel method is returning a new instance of the label which then overwrites the one you had in label variable thus causing a memory leak of the overwritten instance (and overreleasing of the returned instance).
In the code:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake....];
label = [CommonMethods BeautifyLabel:label withText:#"hi" withFont:#"Helvetica" andSize:13 andColor:[UIColor whiteColor]];
label is allocated on the first line, on the second line label is replaed by the call to BeautifyLabel or so the analyzer thinks, not knowing what is done in BeautifyLabel. It can't assume you are returning the same object.
Either do not make the assignment:
[CommonMethods BeautifyLabel:label withText:#"hi" withFont:#"Helvetica" andSize:13 andColor:[UIColor whiteColor]];
or use different label pointer names:
UILabel *labelTemp = [[UILabel alloc] initWithFrame:CGRectMake....];
label = [CommonMethods BeautifyLabel:labelTemp withText:#"hi" withFont:#"Helvetica" andSize:13 andColor:[UIColor whiteColor]];

How to customize MPVolumeView?

I have tried many methods to implement a regular UISlider and control the device volume, but it's all Native-C functions which results in many untraceable bugs.
I tried the MPVolumeView it works like charm, it even controls the device volume even after you close the app, just like the iPod app.
My question is, is there anyway to customize the MPVolumeView with specific colors and images, just like UISlider?
NOTE: I want a legal method without using private undocumented APIs.
UPDATE
As per #Alexsander Akers answer, since the sub views are hidden in MPVolumeView I had to cycle through subviews, get the UISlider and customize it, here is the code.
IBOutlet UISlider *volumeSlider; //defined in <class.h> and connected to a UISlider in Interface Builder
-(void) viewDidLoad {
....
[self setCustomSlider];
....
}
-(void) setCustomSlider{
MPVolumeView *volumeView = [[[MPVolumeView alloc] initWithFrame:[volumeSlider frame]] autorelease];
NSArray *tempArray = volumeView.subviews;
for (id current in tempArray){
if ([current isKindOfClass:[UISlider class]]){
UISlider *tempSlider = (UISlider *) current;
UIImage *img = [UIImage imageNamed:#"trackImage.png"];
img = [img stretchableImageWithLeftCapWidth:5.0 topCapHeight:0];
[tempSlider setMinimumTrackImage:img forState:UIControlStateNormal];
[tempSlider setThumbImage:[UIImage imageNamed:#"thumbImage.png"] forState:UIControlStateNormal];
}
}
[volumeSlider removeFromSuperview];
[self.view addSubview:volumeView];
}
You could try cycling through its subviews and look for a UISlider subclass?
Since iOS 5.0 you can use UIAppearance on a UISlider, even when part of MPVolumeView.
Anywhere in your codebase:
[[UISlider appearanceWhenContainedIn:[MPVolumeView class], nil] setMinimumTrackImage:[[UIImage imageNamed:#"nowplaying_bar_full.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(5, 25, 5, 25)] forState:UIControlStateNormal];
[[UISlider appearanceWhenContainedIn:[MPVolumeView class], nil] setMaximumTrackImage:[[UIImage imageNamed:#"nowplaying_bar_empty.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(5, 25, 5, 25)] forState:UIControlStateNormal];
[[UISlider appearanceWhenContainedIn:[MPVolumeView class], nil] setThumbImage:[UIImage imageNamed:#"nowplaying_player_nob.png"] forState:UIControlStateNormal];
Here a list of some of the other classes that can be implemented using UIAppearance:
https://gist.github.com/mattt/5135521
There are now ways to accomplish this, simply use:
– setMaximumVolumeSliderImage:forState:
– setMinimumVolumeSliderImage:forState:
– setVolumeThumbImage:forState:
Which are slightly different method names than the ones for the vanilla UISlider.
This prevents you from having to cycle through the views and potentially have something break in the future as Apple changes things.
Answer in Swift:
func customSlider() {
let temp = mpVolView.subviews
for current in temp {
if current.isKind(of: UISlider.self) {
let tempSlider = current as! UISlider
tempSlider.minimumTrackTintColor = .yellow
tempSlider.maximumTrackTintColor = .blue
}
}
}
Result:
Try using a Notification, but it looks like Apple is denying them.
[EDIT]
Try this.