This is the code I am using to dynamically change text in my UITextView based on which item is selected in my NSArray.
NSMutableString *flavorsText = [NSMutableString string];
for (NSString* preworkout in self.preWorkout.flavors) {
[flavorsText appendFormat:#"%#\n", preworkout];
}
self.flavorsTextView.text = flavorsText;
I am curious as to how I can change the link behind a single button based on the link that is typed into the NSArray. I want it to have the same functionality as this code above basically.
You need to store the URL somewhere. Add a property to your class:
#property (nonatomic, strong) NSURL *storeURL;
The button code should look something like this:
- (IBAction)buyNow:(id)sender
{
[someWebView loadRequest:[NSURLRequest requestWithURL:self.storeURL]];
}
When the user changes the selection, update the storeURL property with the new URL.
Basically you have an array, someArrayOfLinks, that contains NSString url strings, correct?
So, as you know arrays are based on indexes, so someArrayOfLinks[9] gives you the 10th item in the array (starts at 0). All UIView objects and their subclasses feature a tag property that holds an integer. So, what I'd do is something like this:
Wherever you are setting the flavors:
self.buyNowButton.tag = someInteger;
Then, when they tap the button
- (IBAction)didSelectBuyNowButton:(UIButton *)sender {
NSString *urlPath = someArrayOfLinks[sender.tag];
NSURL *url = [NSURL URLWithString:urlPath];
[[UIApplication sharedApplication] openUrl:url];
}
Related
I have created an NSArray from a text file with
void arrayfromfile {
// get a reference to our file
NSString *myPath = [[NSBundle mainBundle]pathForResource:#"CalendarQuotes" ofType:#"txt"];
// read the contents into a string
NSString *myFile = [[NSString alloc]initWithContentsOfFile:myPath encoding:NSUTF8StringEncoding error:nil];
// split our string into an array
NSArray *mySplit = [myFile componentsSeparatedByString:#"\n"];}
Now what I'd like to do is set label.text to mySplit[x] while x< mysplit.count and call it every time a user swipes up.
setlabeltextmethod quote {
if x<mySplit.count {
label.text = mySplit objectatindex x
x+=1
else { label.text = #"thats it folks" }
}
What I'm having trouble with is accessing mySplit from the quote so I can manipulate it to give me the quote at index x.
When I tried to access it from my swipe method:
- (IBAction)swipeUp:(id)sender {
[self doAnimationUp];
NSLog (#"swipedUp");
NSLog(#"array%#" , [mySplit objectAtIndex:0]);
NSLog(#"arraycreated");
//I'm using NSLog for debug purposes but this is where I would setlabeltext.text to mySplit objectAtIndex
}
I get array[null].
Your mySplit variable is local to arrayfromfile, so once that method returns the variable has gone. There is more than one approach to solving this. One is making it an instance variable, that is a variable that belongs to your current class instance and is visible to every instance method. Start you implementation like this:
#implementation MyClassName
{
NSArray *mySplit;
}
Now set the variable in the instance method arrayfromfile and read it in the instance method swipeUp - both calls must be made in the same instance of your class, each instance has its own set of instance variables.
Other options include adding a property to the class or, if you must, a global variable of some kind.
HTH
I know how to make a phone call, but I'm trying to call certain people depending on which table view cell is selected. I viewed this question but with no success. In my viewDidLoad method, I created a NSDictionary for the phone numbers:
NSString *path = [[NSBundle mainBundle] pathForResource:#"State" ofType:#"plist"];
// Load the file content and read the data into arrays
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
stateNum = [dict objectForKey:#"Phone"];
I then sent the number that was selected to my detail view controller in the prepareForSegue method:
destViewController.phoneName = [stateNum objectAtIndex:indexPath.row];
I created an IBAction method and successfully linked it to the button in my storyboard:
-(IBAction)phone
{
[[UIApplication sharedApplication]
openURL: [NSURL URLWithString:plistNum]];
}
plistNum is defined in my viewDidLoad method of the detail view controller as:
plistNum = [NSString stringWithFormat:#"tel:%#",stateName];
The app compiles and runs, but when I click the button nothing happens. It worked when I had tel:12345678901 in URLWithString but not now. If anyone has any suggestions I would be happy to listen. I am very, very new to this so if you could explain your answer I would appreciate it. Thanks.
Edit: #rmaddy helped me find my dumb mistake. I had used stateName in the plistNum String instead of phoneName. There were no messages on the console, the string I had created was just not a phone number. Also, I don't have a viewWillAppear method. Will creating this make the program smoother?
I have 2 views, a login view and a main view.
I use SWRevealViewController, and I want automatically display my menu at the startup of the app. I know how display my menu but I don't know how display it just once at startup.
I want to pass a simple String between my Login view and my Main view but without segue, and made a simple test :
if (myPreviousView == "LoginView")
{
// display my menu
}
Another method would be to use NSUserDefault to store your string, which than can be accessed from anywhere within the application.
So, you put your string into NSUserDefaults in your first view:
// Initialize the NSUserDefaults object and an array for data storage
NSUserDefaults *defsData = [NSUserDefaults standardUserDefaults];
NSMutableArray *myArray = [[NSMutableArray alloc] init];
// Add your string to the custom array
NSString *myString = #"My string.";
[myArray addObject:myString];
// Put the array back into UserDefaults for later use
[defsData setObject:myArray forKey:#"Key"]; // Key can be anything
[defsData synchronize];
Now, the array (and the string in it) is available anywhere. So, when you navigate to your second view controller, just initialize an NSUserDefaults and access the string:
NSUserDefaults* defsData = [NSUserDefaults standardUserDefaults];
NSArray *myArray = [defsData objectForKey:#"Key"];
NSLog("This is my stored string: %#", [myArray objectAtIndex:0]);
You can modify the init method of your second view controller to take a custom attribute when you subclass it. So, lets say you created a standard UIViewController (.h and .m files). You can modify the init method of this new class to your liking in the .h file:
- (instancetype)initWithString:(NSString *)string;
And then replace the standard init with the new one in the .m:
- (instancetype)initWithString:(NSString *)string {
}
So, when you call your view controller into existence, you just use this new init method and pass the string you wanted like this:
UIViewController *viewController = [[UIViewController alloc] initWithString:myString];
[self presentViewController:viewController animated:NO completion:nil];
This is a programmatical approach of course, but it should be applied to interface builder easily (unfortunately, as I never use interface builder, I don't know how exactly, but as I said, it should be fairly straightforward to anyone who uses it).
I have an NSMutableDictionary (PerosnsListSections) and a class names Persons
NSMutableDictionary:
Keys are letters like "a,b,m ..."
Values are NSMutableArray
-> NSMutableArray have objects of class Persons
Persons class:
#property (assign,nonatomic) NSInteger pid;
#property (strong,nonatomic) NSString *name;
Now i have PerosnsListSections displayed in UITableView as shown in the image
what I want to achieve is when user types in the search bar first i have to filter the section which is the first letter then to filter the names under that section.
Sorry for my bad English (:
You can first select the correct array in the dictionary by doing:
NSString *firstLetter = [searchString substringWithRange:(NSRange){0,1}];
NSArray *people = PersonsListSection[firstLetter];
Then you can filter down on the people by using NSPredicates:
NSPredicate *namesBeginningWithKeyword = [NSPredicate predicateWithFormat:#"(name BEGINSWITH[cd] $letter)"];
NSArray *filteredPeople = [people filteredArrayUsingPredicate:[namesBeginningWithKeyword predicateWithSubstitutionVariables:#{#"letter": searchString}]]);
The question of how you make that be reflected in the tableview's content is a whole another question though.
Typically, you'll want your view controller to be the UISearchBar's delegate and react to change using the – (void)searchBar:textDidChange: delegate method.
There you could just call your tableview's - reloadData method so it tries recompute its content, calling all of its dataSource method like - numberOfSectionsInTableView: and so forth.
In these methods, in turn, you'll want to check whether some text was entered in the search bar and use the above tips to return the right sections/cells.
I have a button named by
UIButton *button1;
how can i save 'button1' in string? or am i able to save it or not?
You can save its' address in memory only: NSString *but1=[NSString stringWithFormat:#"%#",&button1];, but if you need to get unique indicator of your buttons, you can use its' tags: button1.tag
Or you can create NSMutableDictionary and add buttons for keys, which equals their names.
You can create a macro like this:
#define getVariableName(var) [NSString stringWithFormat:#"%s", #var]
And use it:
NSLOG(#"My variable name is %#", variableName(self.button1));
You'll see
My variable name is button1
No you can't do this, as UIButton is an object and you are declaring UIButton as button1. This will remain static as it holds the reference in memory.
NSString is something that you can chage any time, but for Object and varible declaration you can't change it.
you get button title in string but not saved button outlet in string you save button outlet in id using this you save button title
NSString *btn = Mybutton.titleLabel.text;
for save button outlet
Iboutlet Uibutton *myButton;
id *myBtn=myButton;
Check this
import
#import "objc/runtime.h"
-(IBAction)btnItemListClicked:(id)sender
{
UIButton *btn=sender;
NSString *name = nil;
uint32_t ivarCount;
Ivar *ivars = class_copyIvarList([self class], &ivarCount);
if(ivars)
{
for(uint32_t i=0; i<ivarCount; i++)
{
Ivar ivar = ivars[i];
id pointer = object_getIvar(self, ivar);
if(pointer == sender)
{
name = [NSString stringWithUTF8String:ivar_getName(ivar)];
break;
}
}
free(ivars);
}
NSLog(#"%#", name);
}
Output is:
Printing description of name:
btnconferenceCall
Check this sample demo
ButtonDemo