how can I pass UIColor's name - iphone

I want to know that how can I pass UIColor's name to the specific method ?
EDIT :
- (id) setLabel:(NSString *)text WithColorName:(NSString *)nameOfColor FontName:(NSString *)f_name FontSize:(float)f_size abel:(UILabel *)templbl
{
templbl.backgroundColor = [UIColor ?????];
return templbl;
}
any suggestions ?
Thanks..

NSString *colorStr = #"magenta";
NSString *selectorString = [colorStr stringByAppendingString:#"Color"];
SEL selector = NSSelectorFromString(selectorString);
UIColor *color = [UIColor blackColor];
if ([UIColor respondsToSelector:selector]) {
color = [UIColor performSelector:selector];
}

- (id) setLabel:(NSString *)text WithColorName:(NSString *)nameOfColor FontName:(NSString *)f_name FontSize:(float)f_size abel:(UILabel *)templbl color:(UIColor*) myLabelColor
{
templbl.backgroundColor = myLabelColor;
return templbl;
}

one option is a dictionary, where the name is the key and the color is the value

You can dynamically invoke the color class methods:
- (id) setLabel:(NSString *)text WithColorName:(NSString *)nameOfColor FontName:(NSString *)f_name FontSize:(float)f_size abel:(UILabel *)templbl
{
SEL colorMethod = NSSelectorFromString([NSString stringWithFormat:#"%#Color", [nameOfColor lowercaseString]]);
// Check if this is a valid color first
if ([[UIColor class] respondsToSelector:colorMethod]) {
// Dynamically invoke the class method
UIColor *color = [[UIColor class] performSelector:colorMethod];
templbl.backgroundColor = color;
}
}

Jhaliya's answer will work, it's not actually strictly what you were asking (in your example you don't want to pass a UIColor as a parameter, you just want to pass it's preset string name.
This is a little tricky, since things like [UIColor redColor] are methods, not string parameters. You would have to use NSSelectorFromString to achieve it. Much better to pass a UIColor in as Jhaliya's answer shows.

Related

How to use this method

I want to use one method for setting the textField.layer properties in one method in utility class. And want to call that method from viewController.
// Utility class
+(void) createRoundedBorderToView:(UIView*)view withColor:(UIColor*)color withCornerRadius:(float)cornerRadius withBorderWidth:(int)borderWidth{
view.layer.borderColor = [color CGColor];
view.layer.borderWidth = borderWidth;
view.layer.cornerRadius = cornerRadius;
}
But not getting how to call the method. I tried below, but giving error.
CGFloat cornerRadius = 5.0f;
[Utilities createRoundedBorderToView:_usernameTextField withColor:[UIColor clearColor] withCornerRadius:cornerRadius];
It is giving crash.
[Utilities createRoundedBorderToView:withColor:withCornerRadius:]: unrecognized selector sent to class 0xdbf80
+(void) createRoundedBorderToView:(UIView*)view withColor:(UIColor*)color withCornerRadius:(float)cornerRadius withBorderWidth:(int)borderWidth{
}
In above method to call you need to pass three parameters.
Like:-
[Utilities createRoundedBorderToView:_usernameTextField withColor:[UIColor clearColor] withCornerRadius:cornerRadius withBorderWidth:10];
are you missed param withBorderWidth:(int)borderWidth
you should call for example:
[Utilities createRoundedBorderToView:_usernameTextField withColor:[UIColor clearColor] withCornerRadius:cornerRadius withBorderWidth:1];

iOS setSelectedImageTintColor uicolor not accepted

Following method is accepted if I set UIColor like:
[tabBarController.tabBar setSelectedImageTintColor:[UIColor greenColor]];
However I would like to call it like:
[tabBarController.tabBar setSelectedImageTintColor:colors];
when
- (UIColor *)colors{
UIColor *colorIcon = [UIColor greenColor];
return colorIcon;
}
and program returns an error "undeclared identifier colors". What am I doing wrong? Thanks
Try this instead:
[tabBarController.tabBar setSelectedImageTintColor:[self colors]];

Adding an uneditable text suffix to a UITextField

I have a UITextField that I'd like to add a "?" suffix to all text entered.
The user should not be able to remove this "?" or add text to the right hand side of it.
What's the best way to go about this?
Use the UITextFieldDelegate protocol to alter the string whenever the field is being edited. Here's a quick stab at it; this will need work, but it should get you started.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString * currentText = [textField text];
if( [currentText characterAtIndex:[currentText length] - 1] != '?' ){
NSMutableString * newText = [NSMutableString stringWithString:currentText];
[newText replaceCharactersInRange:range withString:string];
[newText appendString:#"?"];
[textField setText:newText];
// We've already made the replacement
return NO;
}
// Allow the text field to handle the replacement
return YES;
}
You'll probably need to subclass UITextField and override its drawText: method to draw an additional "?" character to the right of the actual text. (Rather than actually add a "?" to the text of the view.
I had this issue and I wrote a subclass to add this functionality: https://github.com/sbaumgarten/UIPlaceholderSuffixField.
Hopefully you have found a solution by now but if you haven't, this should work.
I realize this answer is late, but I found most of these did not work for my scenario. I have a UITextField that I simply want to force to have a suffix that the user cannot edit. However, I don't want to subclass UITextView, modify how it handles drawing, etc. I just want to prevent the user from modifying the suffix.
First, I ensure the suffix is set in the textfield when editing takes place. This could be done any number of ways depending upon your scenario. For mine, I wanted it there from the start, so I simply set the textfield's text property equal to the suffix when the view loads and store off the length of the suffix for later. For example:
- (void)viewDidLoad {
[super viewDidLoad];
myTextField.text = "suffix";
_suffixLength = myTextField.text.length;
}
Then I used the UITextFieldDelegate protocol as Josh suggested above, but use the length of the string and the range to ensure nothing edits the suffix:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// Determine starting location of the suffix in the current string
int suffixLocation = textField.text.length - _suffixLength;
// Do not allow replacing anything in/past the suffix
if (range.location + range.length > suffixLocation)
{
return NO;
}
// Continue with delegate code...
}
This should work for any suffix value you assign to the textfield.
For a single-line UITextField you should be able to measure the size of the NSString (it has a measurement function in there, somewhere) and move a UILabel to the right position.
I would add a method that is called when edit finishes:
`- (void)editDidFinish {
NSString* str=[[NSString alloc] init];
str=myEdit.text;
[str stringByAppendingString:#"?"];
myEdit.text=str;
}`
OK, im definitly too late, but maybe i can help someone out either way:
The intended way to accomplish this is by using a custom NSFormatter. Heres the docs:
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSFormatter_Class/Reference/Reference.html
The basic idea is this: you create a subclass of NSFormatter, and the override at least the two worker methods:
-stringObjectForValue:
this will produce the dipsplay-String from the value stored in the object (i.e. add your questionmark here)
-objectValue:ForString:errorDescription
here, you need to transform the display-string into an object you want to store, i.e. remove the questionmark
The formatter can then be used to convert the data from the stored objects into strings that are suitable for presentation to the user.
The big advantage is that you can use formatters wherever your string will appear in the UI. It is not limited to certain UI-Elements like the solution where you override -drawText in UITextField. Its just hella convenient.
This class method I have written in Objective-C, helps you to add a suffix text to a UITextField.
I order to make it work, you need to initialize the UILabel to the prefix or suffix in your UITextFieldLabel as follow:
myTextField.rightView = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 0.0f, myTextField.frame.size.height)];
myTextField.rightViewMode = UITextFieldViewModeAlways;
[MyClass UpdateUITextFieldSuffix:myTextField withString:#"My Suffix!"];
Once we have the UILabel attached to the UITextField, you can use this class method to update the text, and this text will be automatically resized to fit in the field.
+ (BOOL)UpdateUITextFieldSuffix:(UITextField*)textField withString:(NSString*)string
{
BOOL returnUpdateSuffix = NO;
if (string != nil && [string respondsToSelector:#selector(length)] && [string length] > 0)
{
NSObject *labelSuffix = textField.rightView;
if (labelSuffix != nil && [labelSuffix respondsToSelector:#selector(setText:)])
{
[(UILabel*)labelSuffix setTextAlignment:NSTextAlignmentRight];
[(UILabel*)labelSuffix setText:string];
[(UILabel*)labelSuffix setBackgroundColor:[UIColor redColor]];
{
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
((UILabel*)labelSuffix).font, NSFontAttributeName,nil];
CGRect frame = [((UILabel*)labelSuffix).text boundingRectWithSize:CGSizeMake(0.0f, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributesDictionary
context:nil];
CGSize size = frame.size;
CGRect newFrame = [(UILabel*)labelSuffix frame];
newFrame.size.width = size.width;
[(UILabel*)labelSuffix setFrame:newFrame];
[(UILabel*)labelSuffix setNeedsLayout];
[(UILabel*)labelSuffix layoutIfNeeded];
}
returnUpdateSuffix = YES;
}
}
return returnUpdateSuffix;
}
I have written the following method to achieve the above task of placing non-editable suffix to UITextField:
- (void)setSuffixText:(NSString *)suffix
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
[label setBackgroundColor:[UIColor clearColor]];
[label setFont:[UIFont fontWithName:self.tfdDistance.font.fontName size:self.tfdDistance.font.pointSize]];
[label setTextColor:self.tfdDistance.textColor];
[label setAlpha:.5];
[label setText:suffix];
CGSize suffixSize = [suffix sizeWithFont:label.font];
label.frame = CGRectMake(0, 0, suffixSize.width, self.tfdDistance.frame.size.height);
[self.tfdDistance setRightView:label];
[self.tfdDistance setRightViewMode:UITextFieldViewModeAlways];
}​

Objective-C use typedef enum to set Class behavior, like Cocoa

Im extending the UIButton Class to be able to set the font and color of the UINavigationBarButton ( from this code example: switch on the code )
I goes like this:
#interface NavBarButtonGrey : UIButton
-(id)init;
#end
#implementation NavBarButtonGrey
-(id)init {
if(self = [super init]) {
self.frame = CGRectMake(0, 0, 49.0, 30.0);
self.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
self.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
UIImage *image = [UIImage imageNamed:#"greyNavButton.png"];
UIImage *stretchImage =
[image stretchableImageWithLeftCapWidth:15.0 topCapHeight:0.0];
[self setBackgroundImage:stretchImage forState:UIControlStateNormal];
self.backgroundColor = [UIColor clearColor];
[self setTitleShadowColor:[UIColor blackColor] forState:UIControlStateNormal];
self.titleShadowOffset = CGSizeMake(0, -1);
self.titleLabel.font = [UIFont boldSystemFontOfSize:13];
}
return self;
}
#end
This is ok, but of course not very flexible.
How do I incorporate using a typedef enum (like Apple does) for all the different
colors, fonts and sizes I would like my custom button to conform to.
The only thing I can get out of the interface files from UIKit is that it is done like this:
typedef enum {
RGCustomNavBarButtonStyleBlue,
RGCustomNavBarButtonStyleGrey,
RGCustomNavBarButtonStyleBlack,
RGCustomNavBarButtonStyleGreen,
RGCustomNavBarButtonStyleRed,
} RGCustomNavBarButtonStyle;
How to get from that and into a working implementation that takes font, size, color etc. from the values of the enum through the constructor(initWithStyle)?
Does one overload constructors in Objective C? multiple constructors?
Hope it makes sense and thank you for any help given:)
To expand on what ennuikiller said above, I was taught (Hillegass's book) to pick one initializer—usually the one with the most options, like your initWithFont:andColor:—and have the other initializers call it. That main initializer is referred to as the designated initializer.
So your code would have a fully-implemented initWithFont:andColor: that calls [super init], and then you'd also have an initWithFont: that looks something like this:
-(MyClass) initWithFont: (UIFont) font
{
[self initWithFont:font andColor:RGCustomNavBarButtonStyleBlack];
}
Then your initWithFont:andColor: would handle all the other setup and calling [super init].
You can have multiple constructors such as;
-(MyClass) initWithFont: (UIFont) font;
-(MyClass) initWithFonmt: (UIFont) font andColor: (UIColor) color;
etc.
Then call [super init] as the first line in each of your custom constructors.

How to share constants between Interface Builder and the code?

I wonder if there is a way to use constants in Interface Builder, in order to avoid manually setting the same color at different places for example (it could be a very tedious job sometimes...)
Currently I set the color in the code and use #define to setup the color, but obviously IB can't use #define...
I have worked around this issue by subclassing the various controls to ensure the same style throughout the app. The drawback is that you can not see the style in interface builder only a wireframe.
For example I have a
#interface MyButton : UIButton
#end
#implementation MyButton
-(void) initialize{
self.backgroundColor = [UIColor MyButonColor]; // Using a category on UIColor
}
- (id)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
[self initialize];
}
return self;
}
- (id)initWithCoder:(NSCoder *)decoder {
if (self = [super initWithCoder:decoder]) {
[self initialize];
}
return self;
}
I think the easiest way to do this would be to create a category on the UIColor class and create a class method on it. For example:
Place this in a header file (e.g. UIColor+CustomColors.h):
#interface UIColor ( CustomColors )
+ (UIColor *)myCustomColor;
#end
Place this in an implementation file (e.g. UIColor+CustomColors.m)
#implementation UIColor ( CustomColors )
+ (UIColor *)myCustomColor
{
return [UIColor colorWithRed:0.2 green:0.5 blue:0.2 alpha:1.0];
}
#end
Then you have access to the class method anywhere in your code like so:
...
self.view.backgroundColor = [UIColor myCustomColor];
...
See Apple's documentation on Categories for more info.
Alternatively, you can save swatches of color through the system color palette. To do this you simply call up the system color palette, select a color and drag it into the grid of colors.
These colors are now available in not only every Interface Builder document you create, but any application that makes use of the system color palette.
color palette http://img.skitch.com/20091030-dhh3tnfw5d8hkynyr7e5q3amwg.png