How do I retrieve named objects denoted by NSStrings? - ios

I have a set of NSString values like this:
self.dataArray = #[#"blue", #"orange", #"green", #"red", #"yellow"];
and would like to be able to do something like (after getting one of the above colors set to self.colorString):
self.view.backgroundColor=[UIColor self.colorString + Color];
but obviously can't do that. What is a possible way?

A nearly universal way:
NSDictionary *colors = #{
#"red": [UIColor redColor],
#"green": [UIColor greenColor],
#"blue": [UIColor blueColor]
};
NSString *name = #"blue";
UIColor *c = colors[name];
A truly universal way:
NSString *selName = [NSString stringWithFormat:#"%#Color", name];
SEL sel = NSSelectorFromString(selName);
UIColor *color = [[UIColor class] performSelector:sel];

You can try something like this:
SEL myColor = NSSelectorFromString([NSString stringWithFormat:#"%#Color", self.colorString]);
self.view.backgroundColor = [[UIColor class] performSelector:myColor]

Try to store associate your data with the colors in a dictionary:
UIColor *blue = [UIColor blueColor];
UIColor *red = [UIColor redColor];
NSDictionary *colors = #{#"blue" : blue, #"red" : red};
UITextField *pinga = [[UITextField alloc]init];
pinga.textColor = [colors objectForKey:#"red"];

Related

How to get text from all text fields created inside for loop in ios

I created Textfields like below
for (DataSourceForController *ds in _dataArray)
{
NSString *name = ds.labelName;
NSString *bits = ds.textLabelPlceholder;
_paramNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.frame.size.width*0, (self.frame.size.height*0.15)+i, self.frame.size.width*0.45,self.frame.size.height*0.05)];
_paramNameLabel.text = name;
_paramNameLabel.textColor = [UIColor blueColor];
_paramNameLabel.textAlignment = NSTextAlignmentCenter;
[self addSubview:_paramNameLabel];
_paramValue = [[UITextField alloc]initWithFrame:CGRectMake(self.frame.size.width*0.45, (self.frame.size.height*0.15)+i, self.frame.size.width*0.55,self.frame.size.height*0.05)];
_paramValue.placeholder = bits;
_paramValue.textAlignment= NSTextAlignmentCenter;
_paramValue.delegate = self;
_paramValue.backgroundColor = [UIColor colorWithRed:35/255.0 green:185/255.0 blue:235/255.0 alpha:1];
[self addSubview:_paramValue];
i=self.frame.size.height*.1+i;
}
How can i get the text from each textfield like _paramVlue.text
You can add UITextField in NSMutableArray. Try below code:
NSMutableArray *textFieldArr = [NSMutableArray alloc]]init;
for (DataSourceForController *ds in _dataArray)
{
NSString *name = ds.labelName;
NSString *bits = ds.textLabelPlceholder;
_paramNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.frame.size.width*0, (self.frame.size.height*0.15)+i, self.frame.size.width*0.45,self.frame.size.height*0.05)];
_paramNameLabel.text = name;
_paramNameLabel.textColor = [UIColor blueColor];
_paramNameLabel.textAlignment = NSTextAlignmentCenter;
[self addSubview:_paramNameLabel];
_paramValue = [[UITextField alloc]initWithFrame:CGRectMake(self.frame.size.width*0.45, (self.frame.size.height*0.15)+i, self.frame.size.width*0.55,self.frame.size.height*0.05)];
_paramValue.placeholder = bits;
_paramValue.textAlignment= NSTextAlignmentCenter;
_paramValue.delegate = self;
_paramValue.backgroundColor = [UIColor colorWithRed:35/255.0 green:185/255.0 blue:235/255.0 alpha:1];
[self addSubview:_paramValue];
[textFieldArr addObject:_paramValue];
i=self.frame.size.height*.1+i;
}
Now suppose yow want to get text of UITextField at index 2 then write below line:
NSString *str = [(UITextField *)[textFieldArr objectAtIndex:2] text];
Hope this will help you.
I found another easy way
for (UITextField *feild in [self subviews])
{
if ([feild isKindOfClass:[UITextField class]])
{
NSLog(#"Text = %# ",feild.text);
}
}

Link tap color for TTTAttributedLabel

I am using a TTTAttributedLabel in my project. I have managed to change the default color and underlining for any link that I create by modifying the link attributes.
NSArray *pKeys = [[NSArray alloc] initWithObjects:(id)kCTForegroundColorAttributeName,
(id)kCTUnderlineStyleAttributeName
, nil];
NSArray *pObjects = [[NSArray alloc] initWithObjects:pAlertColor,[NSNumber numberWithInt:
kCTUnderlineStyleNone], nil];
NSDictionary *pLinkAttributes = [[NSDictionary alloc] initWithObjects:pObjects
forKeys:pKeys];
self.alertMessage.linkAttributes = pLinkAttributes;
self.alertMessage.activeLinkAttributes = pLinkAttributes;
However, I have noticed that when I tap on the link, it turns red momentarily as any other link does when tapped. I need to change this color. Any clues to how that might be done?
Swift 2 Solution:
Specifically, need to set activeLinkAttributes, see below example:
private func subscriptionNoticeWithDelegate(delegate:TTTAttributedLabelDelegate) -> TTTAttributedLabel {
let subscriptionNotice:String = "To turn on all notifications, subscribe to our monthly " +
"service ($0.99/month). If you have already subscribed, please restore your purchase."
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineHeightMultiple = 1.2
let subscriptionNoticeAttributedString = NSAttributedString(string:subscriptionNotice, attributes: [
NSFontAttributeName: UIFont(name:"HelveticaNeue-Light", size:15)!,
NSParagraphStyleAttributeName: paragraphStyle,
NSForegroundColorAttributeName: UIColor.grayColor().CGColor,
])
let subscriptionNoticeLinkAttributes = [
NSForegroundColorAttributeName: UIColor.grayColor(),
NSUnderlineStyleAttributeName: NSNumber(bool:true),
]
let subscriptionNoticeActiveLinkAttributes = [
NSForegroundColorAttributeName: UIColor.grayColor().colorWithAlphaComponent(0.80),
NSUnderlineStyleAttributeName: NSNumber(bool:true),
]
let subscriptionNoticeLabel:TTTAttributedLabel = TTTAttributedLabel(frame:CGRectZero)
subscriptionNoticeLabel.delegate = delegate
subscriptionNoticeLabel.numberOfLines = 0
subscriptionNoticeLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
subscriptionNoticeLabel.textInsets = UIEdgeInsets(top:10, left:15, bottom:0, right:15)
subscriptionNoticeLabel.setText(subscriptionNoticeAttributedString)
subscriptionNoticeLabel.linkAttributes = subscriptionNoticeLinkAttributes
subscriptionNoticeLabel.activeLinkAttributes = subscriptionNoticeActiveLinkAttributes
let subscribeLinkRange = (subscriptionNotice as NSString).rangeOfString("subscribe")
let subscribeURL = NSURL(string:kSubscriptionNoticeSubscribeURL)!
subscriptionNoticeLabel.addLinkToURL(subscribeURL, withRange:subscribeLinkRange)
let restoreLinkRange = (subscriptionNotice as NSString).rangeOfString("restore")
let restoreURL = NSURL(string:kSubscriptionNoticeRestoreURL)!
subscriptionNoticeLabel.addLinkToURL(restoreURL, withRange:restoreLinkRange)
return subscriptionNoticeLabel
}
You will like to look at TTTAttributedLabel documentation, specifically at activeLinkAttributes
activeLinkAttributes
#property (nonatomic, strong) NSDictionary *activeLinkAttributes
Discussion
A dictionary containing the NSAttributedString attributes to be
applied to links when they are in the active state. If nil or an empty
NSDictionary, active links will not be styled. The default active link
style is red and underlined.
Declared In
TTTAttributedLabel.h
You should do something like this
NSMutableDictionary *mutableActiveLinkAttributes = [NSMutableDictionary dictionary];
[mutableActiveLinkAttributes setObject:[NSNumber numberWithBool:NO] forKey:(NSString *)kCTUnderlineStyleAttributeName];
[mutableActiveLinkAttributes setObject:[UIColor greenColor] forKey:(NSString *)kCTForegroundColorAttributeName];
label.activeLinkAttributes = [NSDictionary dictionaryWithDictionary:mutableActiveLinkAttributes];
For Swift 4:
let activeLinkAttributes = NSMutableDictionary(dictionary: attributedLabel.activeLinkAttributes)
activeLinkAttributes[NSAttributedStringKey.foregroundColor] = UIColor.blue
attributedLabel.activeLinkAttributes = activeLinkAttributes as NSDictionary as! [AnyHashable: Any]
For Swift 3:
let activeLinkAttributes = NSMutableDictionary(dictionary: attributedLabel.activeLinkAttributes)
activeLinkAttributes[NSForegroundColorAttributeName] = UIColor.blue
attributedLabel.activeLinkAttributes = activeLinkAttributes as NSDictionary as! [AnyHashable: Any]
Full code to set TTTAttributedLabel in Objective-C
#import "TTTAttributedLabel.h"
#property (weak, nonatomic) IBOutlet TTTAttributedLabel *attributedLable;
- (void)viewDidLoad {
[super viewDidLoad];
[self setup];
}
- (void)setup {
_attributedLable.numberOfLines = 0;
NSString *strTC = #"Terms and Condition";
NSString *strPP = #"Privacy Policy";
NSString *string = [NSString stringWithFormat:#"By click continue I agree to %# and %#.",strTC,strPP];
NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle alloc];
paragraphStyle.lineHeightMultiple = 1.2;
NSAttributedString *fullAttributedString = [[NSAttributedString alloc] initWithString:string attributes:#{
NSFontAttributeName : [UIFont fontWithName:IZFontNameLatoRegular size:15.0],
NSParagraphStyleAttributeName : paragraphStyle
}];
[_attributedLable setTextAlignment:NSTextAlignmentCenter];
[_attributedLable setAttributedText:fullAttributedString];
NSRange rangeTC = [string rangeOfString:strTC];
NSRange rangePP = [string rangeOfString:strPP];
NSDictionary *ppActiveLinkAttributes = #{NSForegroundColorAttributeName : [UIColor blueColor], NSUnderlineStyleAttributeName: #(NSUnderlineStyleNone)};
NSDictionary *ppLinkAttributes = #{NSForegroundColorAttributeName : [UIColor blueColor], NSUnderlineStyleAttributeName: #(NSUnderlineStyleNone)};
_attributedLable.activeLinkAttributes = ppActiveLinkAttributes;
_attributedLable.linkAttributes = ppLinkAttributes;
NSURL *urlTC = [NSURL URLWithString:#"action://TC"];
NSURL *urlPP = [NSURL URLWithString:#"action://PP"];
[_attributedLable addLinkToURL:urlTC withRange:rangeTC];
[_attributedLable addLinkToURL:urlPP withRange:rangePP];
_attributedLable.textColor = [UIColor blackColor];
_attributedLable.delegate = self;
}
//Delegate Method
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
if ([url.absoluteString isEqualToString:#"action://TC"]) {
NSLog(#"terms and conditions click");
}
else if ([url.absoluteString isEqualToString:#"action://PP"]){
NSLog(#"privacy policy click");
}
}
Note : Install Pod file : pod 'TTTAttributedLabel'
You can use an attribute "activeLinkAttributes"
NSMutableDictionary* attributes = [NSMutableDictionary dictionaryWithDictionary:self.attributedLabel.activeLinkAttributes];
[attributes setObject:(__bridge id)[UIColor blueColor].CGColor forKey:(NSString*)kCTForegroundColorAttributeName];
self.attributedLabel.activeLinkAttributes = attributes;
For reference, Not changing link color when tapping.
Just disable active link color by code below.
self.tttAttributedLabel.inactiveLinkAttributes = nil;

UILabel updating text, but won't remove old text

EDIT: I figured out that i needed to remove subviews, once the view did disappear
[[self.scrollView subviews]makeObjectsPerformSelector:#selector(removeFromSuperview)];
My problem is that I have an UILabel which updates the text correctly, but won't remove the old text. I think maybe it's because there are 2 UILabels on top of each other, here is a picture of it:
And here is my code. I can't see where the duplicate is:
for (int i = 0; i < array1.count; i++) {
NSNumber *myNumber = [myscoretext objectAtIndex:i];
float myScore = myNumber.floatValue;
NSNumber *levelNumber = [neededscoretext objectAtIndex:i];
float levelScore = levelNumber.floatValue;
for (int i = 0; i < array1.count; i++) {
NSNumber *myNumber = [myscoretext objectAtIndex:i];
float myScore = myNumber.floatValue;
NSNumber *levelNumber = [neededscoretext objectAtIndex:i];
float levelScore = levelNumber.floatValue;
float progressScore = ((float)myScore/(float)levelScore);
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * i;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
UIView *subview = [[UIView alloc] initWithFrame:frame];
subview.backgroundColor = [UIColor clearColor];
NSArray *colorArray = [NSArray arrayWithObjects:edmeral, turqouise, orange, red, nil];
// Labeled progress views
self.labeledProgressView = [[DALabeledCircularProgressView alloc]
initWithFrame:CGRectMake(25.0f, 20.0f, 100.0f, 100.0f)];
self.labeledProgressView.roundedCorners = NO;
self.labeledProgressView.trackTintColor = [UIColor colorWithWhite:1.0f alpha:0.8];
imageLevel = [[UIImageView alloc] initWithFrame:CGRectMake(25.0f, 20.0f, 100.0f, 100.0f)];
imageLevel.backgroundColor = [UIColor clearColor];
self.Scoreint = [[UILabel alloc] initWithFrame:CGRectMake(-25.0f, 130, 195, 21)];
self.Scoreint.backgroundColor = [UIColor clearColor];
self.Scoreint.textColor = [UIColor blackColor];
[self.Scoreint setFont:[UIFont fontWithName:#"HelveticaNeue-Thin" size:15]];
self.Scoreint.textAlignment = NSTextAlignmentCenter;
self.Scoreint.text = #"";
if (myScore == 0) {
NSString *scoreString = [NSString stringWithFormat:#"0 / %5ld", (long)levelScore];
[self.Scoreint setText:scoreString];
}
else {
NSString *scoreString = [NSString stringWithFormat:#"%5li / %5li", (long)myScore, (long)levelScore];
[self.Scoreint setText:scoreString];
}
[subview addSubview:Scoreint];
I hope some of you guys can help me out with this! :)
the other way, you should do it, it's remove the label from superView everytime, before you initialize it.
You modify the code like this,
if(self.Scoreint) {
[self.Scoreint removeFromSuperview];
}
self.Scoreint = [[UILabel alloc] initWithFrame:CGRectMake(-25.0f, 130, 195, 21)];
self.Scoreint.backgroundColor = [UIColor clearColor];
self.Scoreint.textColor = [UIColor blackColor];
[self.Scoreint setFont:[UIFont fontWithName:#"HelveticaNeue-Thin" size:15]];
self.Scoreint.textAlignment = NSTextAlignmentCenter;
self.Scoreint.text = #"";
that happens because you instantiate the UILabel each time, You have to instantiate the it only once, outside the for loop, and then just change the title.
This might work, i haven't tried it
self.Scoreint = [[UILabel alloc] initWithFrame:CGRectMake(-25.0f, 130, 195, 21)];
self.Scoreint.backgroundColor = [UIColor clearColor];
self.Scoreint.textColor = [UIColor blackColor];
[self.Scoreint setFont:[UIFont fontWithName:#"HelveticaNeue-Thin" size:15]];
self.Scoreint.textAlignment = NSTextAlignmentCenter;
self.Scoreint.text = #"";
for (int i = 0; i < array1.count; i++) {
NSNumber *myNumber = [myscoretext objectAtIndex:i];
float myScore = myNumber.floatValue;
NSNumber *levelNumber = [neededscoretext objectAtIndex:i];
float levelScore = levelNumber.floatValue;
for (int i = 0; i < array1.count; i++) {
NSNumber *myNumber = [myscoretext objectAtIndex:i];
float myScore = myNumber.floatValue;
NSNumber *levelNumber = [neededscoretext objectAtIndex:i];
float levelScore = levelNumber.floatValue;
float progressScore = ((float)myScore/(float)levelScore);
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * i;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
UIView *subview = [[UIView alloc] initWithFrame:frame];
subview.backgroundColor = [UIColor clearColor];
NSArray *colorArray = [NSArray arrayWithObjects:edmeral, turqouise, orange, red, nil];
// Labeled progress views
self.labeledProgressView = [[DALabeledCircularProgressView alloc]
initWithFrame:CGRectMake(25.0f, 20.0f, 100.0f, 100.0f)];
self.labeledProgressView.roundedCorners = NO;
self.labeledProgressView.trackTintColor = [UIColor colorWithWhite:1.0f alpha:0.8];
imageLevel = [[UIImageView alloc] initWithFrame:CGRectMake(25.0f, 20.0f, 100.0f, 100.0f)];
imageLevel.backgroundColor = [UIColor clearColor];
[self.Scoreint setFont:[UIFont fontWithName:#"HelveticaNeue-Thin" size:15]];
self.Scoreint.textAlignment = NSTextAlignmentCenter;
self.Scoreint.text = #"";
if (myScore == 0) {
NSString *scoreString = [NSString stringWithFormat:#"0 / %5ld", (long)levelScore];
[self.Scoreint setText:scoreString];
}
else {
NSString *scoreString = [NSString stringWithFormat:#"%5li / %5li", (long)myScore, (long)levelScore];
[self.Scoreint setText:scoreString];
}
[subview addSubview:Scoreint];
In similar situation, the property of UIView’s visual appearance helped me. Try this:
self.Scoreint.clearsContextBeforeDrawing = true

Save user settings in iPhone/iPad app [duplicate]

This question already has answers here:
How to store custom objects in NSUserDefaults
(7 answers)
Closed 8 years ago.
In my app I let users to pick a colour of background, tint and text. How can I save this settings after the app is closed? I mean when user again starts the app he wants to see the background, tint and text colour from previous usage.
This is how I have set the colours.
self.BackgroundView.backgroundColor = [UIColor colorWithRed:248.0/255.0 green:242.0/255.0 blue:229.0/255.0 alpha:1.0];
[[[self navigationController] navigationBar] setTintColor:[UIColor colorWithRed:103.0/255.0 green:10.0/255.0 blue:10.0/255.0 alpha:1.0]];
self.QuoteText.textColor = [UIColor colorWithRed:131.0/255.0 green:21.0/255.0 blue:21.0/255.0 alpha:1.0];
Trying to solve by following Greg's (probably the right) answer gives SIGABRT error by clicking on following button:
- (IBAction)setcolor:(id)sender {
UIColor *backgroundColor = [UIColor colorWithRed:230.0/255.0 green:230.0/255.0 blue:220.0/255.0 alpha:1.0];
self.BackgroundView.backgroundColor = backgroundColor;
UIColor *tintColor = [UIColor colorWithRed:129.0/255.0 green:165.0/255.0 blue:148.0/255.0 alpha:1.0];
[[[self navigationController] navigationBar] setTintColor:tintColor];
UIColor *textColor = [UIColor colorWithRed:0.0/255.0 green:98.0/255.0 blue:139.0/255.0 alpha:1.0];
self.QuoteText.textColor = textColor;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:backgroundColor forKey:#"BACKGCOLOR"];
[defaults setObject:tintColor forKey:#"TINTCOLOR"];
[defaults setObject:textColor forKey:#"TEXTCOLOR"];
[defaults synchronize];
}
If user pick up colour instead of
self.BackgroundView.backgroundColor = [UIColor colorWithRed:248.0/255.0 green:242.0/255.0 blue:229.0/255.0 alpha:1.0];
You can do
UIColor *backgroundColor = [UIColor colorWithRed:248.0/255.0 green:242.0/255.0 blue:229.0/255.0 alpha:1.0];
self.BackgroundView.backgroundColor = backgroundColor;
NSData *backgroundColorData = [NSKeyedArchiver archivedDataWithRootObject:backgroundColor];
UIColor *tintColor = [UIColor colorWithRed:103.0/255.0 green:10.0/255.0 blue:10.0/255.0 alpha:1.0];
[[[self navigationController] navigationBar] setTintColor:tintColor];
NSData *tintColorData = [NSKeyedArchiver archivedDataWithRootObject: tintColor];
UIColor *textColor = [UIColor colorWithRed:131.0/255.0 green:21.0/255.0 blue:21.0/255.0 alpha:1.0];
self.QuoteText.textColor = textColor;
NSData *textColorData = [NSKeyedArchiver archivedDataWithRootObject: textColor];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject: backgroundColorData forKey:#"BACKGCOLOR"];
[defaults setObject:tintColorData forKey:#"TINTCOLOR"];
[defaults setObject:textColorData forKey:#"TEXTCOLOR"];
[defaults synchronize];
You do the same for tint and text colour (just use different key).
In the view controller where you want to change your view colour in viewDidLoad you do:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *backgColorData = [defaults objectForKey:#"BACKGCOLOR"];
UIColor *backgColor = [NSKeyedUnarchiver unarchiveObjectWithData:backgColorData];
NSData *tintColorData = [defaults objectForKey:#"TINTCOLOR"];
UIColor *tintColor = [NSKeyedUnarchiver unarchiveObjectWithData:tintColorData];
NSData *textColorData = [defaults objectForKey:#"TEXTCOLOR"];
UIColor *textColor = [NSKeyedUnarchiver unarchiveObjectWithData: textColorData];
if (backgColor)
self.BackgroundView.backgroundColor = backgColor;
if (tintColor)
[[[self navigationController] navigationBar] setTintColor:tintColor];
if (textColor)
self.QuoteText.textColor = textColor;
Apple is providing the NSUserDefaults for this, it does act like the preferences for your user / application. Example taken from here
Saving :
NSString *valueToSave = #"someValue";
[[NSUserDefaults standardUserDefaults]
setObject:valueToSave forKey:#"preferenceName"];
To get it back later :
NSString *savedValue = [[NSUserDefaults standardUserDefaults]
stringForKey:#"preferenceName"];
Test using nsuserdefaults to save the settings or, write to a plist.

How to set color by pointer to color name?

Normal, I often setBackgound color by:
aView.backgroundColor = [UIColor redColor];
Now I keep all color name in an NSArray:
colorsArray = [[NSMutableArray alloc] initWithObjects:
#"blackColor",
#"darkGrayColor",
#"lightGrayColor",
#"whiteColor",
#"grayColor",
#"redColor",
#"greenColor",
#"blueColor",
#"cyanColor",
#"yellowColor",
#"magentaColor",
#"orangeColor",
#"purpleColor",
#"brownColor",
nil];
And I want to set background by a NSString pointer like that
NSInteger i = 0;
for (aView in viewArray) {
NSString *colorName = [colorsArray objectAtIndex:i];
aView.backgroundColor = color with colorName;//Can't find a method to set
i++;
}
I check UIColor class and can't find any method to set color with pointer to colorName.
Please help! Any another way? Thanks!
A little bit of reflection and the medicine goes down...
NSInteger i = 0;
for (aView in viewArray) {
NSString *colorName = [colorsArray objectAtIndex:i];
aView.backgroundColor = [[UIColor class] performSelector:NSSelectorFromString(colorName)];
i++;
}
aView.backgroundColor = [UIColor performSelector:NSSelectorFromString(colorName)];

Resources