Xcode IOS Create 3 buttons to replace keyboard and text box - ios

I am using an app to lock, unlock, and open the trunk of my car. The only problem is that I can't figure out how to modify the Xcode project so there are 3 buttons. Basically right now if I type "U" then enter- the car unlocks, "L" then enter- the car locks, and "T" then enter- the trunk opens. I want to add three buttons that simulate these three things and eliminate the typing all together. If you want to see my adruino or xcode project code I can upload those. I have put some code about the text box below.
BOOL)textFieldShouldReturn:(UITextField *)textField
{
NSString *text = textField.text;
NSNumber *form = [NSNumber numberWithBool:NO];
NSString *s;
NSData *d;
if (text.length > 16)
s = [text substringToIndex:16];
else
s = text;
d = [s dataUsingEncoding:NSUTF8StringEncoding];
if (bleShield.activePeripheral.state == CBPeripheralStateConnected) {
[bleShield write:d];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:text, TEXT_STR, form, FORM, nil];
[tableData addObject:dict];
[_tableView setContentOffset:CGPointMake(0, CGFLOAT_MAX)];
NSLog(#"%f", _tableView.contentOffset.y);
[self.tableView reloadData];
}
textField.text = #"";
return YES;
Thanks for the help!

Your view controller probably has a textFieldShouldReturn method which is taking the string value from the text field and building a parameter to a call that initiates sending the command. If not this method then perhaps its action method linked to the text field.
You'll need to duplicate parts of that code into a method that receives a string parameter instead of taking it from the text field, say named sendLockCommand:(NSString *)commandString (assuming you're coding in Objective-C, also like that repo).
Make action methods for your buttons, something like lockDoors, unlockDoors, openTrunk, in each call [self sendLockCommand:#"L"], each with the appropriate string. Wire up the buttons to those actions and you're good to go.

Related

how to insert number like in stack and delete like pop

I am using buttons and I assigned tag 0 to 10 . Then I made an action to get the clicked button's tag, and now I want to display the tag in a label . Also I have a cancel button C. If user wants to delete any number, he can click C button that I want to remove number from the label .
This is my screenshot to touch the number
- (void)viewDidLoad {
[super viewDidLoad];
self.title = #"Ezywire";
addnum=[[NSMutableArray alloc]init];
numbber=[[NSString alloc]init];
}
- (IBAction)NumberAction:(id)sender {
NSInteger tagvalue = [sender tag];
NSString *current=[NSString stringWithFormat:#"%ld", (long)tagvalue];
[addnum addObject:current];
NSString *temp;
for ( int i=0; i<[addnum count]; i++) {
numbber=[numbber stringByAppendingString:[addnum objectAtIndex:i]];
}
NSLog(#"data===%#",numbber);
ValueLable.text= numbber;
}
But in the label I am getting repeated number like this. How to implement this.
For example if user enters 2 then in the label
2
then he enters 7 then in the label
27
then he entered 9 then in the label
279
........ like this .
If user clicks C, then it remove from label last value is (last value removed)
27
The problem in your code is that numbber is initialized when the view is loaded, and never gets cleared again. However, each time a button is pressed, the whole addnum of digits gets appended to num again, creating repeated digits.
Fix this by removing num as an instance variable, making it a local to NumberAction: method, and setting it to an empty string every time the number is pressed.
Since you are planning to support the clearing action as well, you should make a private method that combines the digits from addnum array into a string. This way your NumberAction: and ClearAction would share the code that formats the array and sets the label. Your NumberAction: method would append a number and call FormatAndSetLabel, while the ClearAction method would remove the last digit if it is available, and call FormatAndSetLabel as well:
- (IBAction)NumberAction:(id)sender {
NSInteger tagvalue = [sender tag];
NSString *current=[NSString stringWithFormat:#"%ld", (long)tagvalue];
[addnum addObject:current];
[self FormatAndSetLabel];
}
- (IBAction)ClearAction:(id)sender {
if (!addnum.count) return;
[addnum removeLastObject];
[self FormatAndSetLabel];
}
-(void)FormatAndSetLabel {
NSMutableString *temp = [NSMutableString string];
for ( int i=0; i<[addnum count]; i++) {
[temp appendString:addnum[i]];
}
ValueLable.text= temp;
}
Also it might be interesting for you to have a look at Paul's Hegarty Stanford iOS development course (iPad and iPhone Application Development, Fall 2011)
https://itunes.apple.com/ru/itunes-u/ipad-iphone-application-development/id473757255?mt=10
Calculator app is used here as an example. Must see for the beginners.

iOS - Wireless Communication Lagging

So I'm making a game that involves wireless communication between multiple iPhones, with one being the host. I am attempting to do so via the MultipeerConnectivity framework, and I've made a MCManager class (an instance of which I put into appDelegate so it's available throughout the app) to handle sending data from one system to another. This is how sending is implemented in my code:
- (void) sendState: (NSString*) str;
//used by the host to send commands to the other connected systems
{
if(appDelegate.mcManager.connected && iAmHost){
NSData *dataToSend = [str dataUsingEncoding: NSUTF8StringEncoding];
NSArray *allPeers = appDelegate.mcManager.session.connectedPeers;
NSError *error;
[appDelegate.mcManager.session sendData:dataToSend
toPeers:allPeers
withMode:MCSessionSendDataReliable
error:&error];
if (error) {
NSLog(#"%#", [error localizedDescription]);
}
}
}
and when the subordinate systems receive the data, MCManager sends the Notification Center a notification and my class, which is looking for that particular notification, grabs it and executes this:
-(void)didReceiveDataWithNotification:(NSNotification *)notification{
if(!iAmHost){
NSData *receivedData = [[notification userInfo] objectForKey:#"data"];
NSString *action = [[NSString alloc] initWithData: receivedData encoding:NSUTF8StringEncoding];
NSLog(#"Recieved:");
NSLog(action); //for debugging purposes, and figuring out timing
//decide how to act depending on the string given
if([action containsString:#"ChangeMaxScore"]){
//the string was formatted as, for example, "ChangeMaxScore105"
NSString* valueStr = [action substringFromIndex:14];
maxScore = (int)[valueStr integerValue];
[self changeMaxScore]; //this method changes the label text that shows the user the value of maxScore
}
else if([action containsString:#"ChangePlayerNo"]){
//strings are formatted as "ChangePlayerNo2" for the second segment in a segmented control with the segments "2", "3", "4"
//so it would be referring to four players
NSString *valueStr = [action substringFromIndex:14];
[playerNumberSegmentedControl setSelectedSegmentIndex: [valueStr integerValue]];
playerNumber = playerNumberSegmentedControl.selectedSegmentIndex + 2;
[self changePlayerNumber];
//Players can either be human or a type of AI (AI-1,AI-2,etc.)
//the segmented control where you choose this is invisible unless that player number is playing
//so this method sets that segmented control visible and interactable (by adding it to the view)
//and removes those segmented controls not in use from the view
}
else if([action containsString:#"ChangeP0State"]){
//changes the value of the first player's segmented control (Human, AI-1, AI-2, etc.
NSString* valueStr = [action substringFromIndex:13];
AIControl0.selectedSegmentIndex = (int)[valueStr integerValue];
}
...
else if([action containsString:#"StartGame"])
[self newGame];
//this method starts the game and, in the process, pushes another view controller
}
}
My issue is that these actions, on the receiving end, are very laggy. For changing the number of players, for instance, the receiver NSLogs "Received: ChangePlayerNo1", and the segmented control on-screen changes its selected segment to the second one, but the stuff that's supposed to show up at that point...doesn't. And when I send the "StartGame" command, the receiver NSLogs that it has received it, I have to wait thirty seconds for it to actually start the game like it was asked.
This delay makes it very hard to test whether my wireless methods are working or not (it works on the host's side, mostly because the host is changing them manually, not responsively - also, all of this works on the other side of my program, which is just the game without wireless support, with several players/AIs on a single screen) and, if not fixed, will definitely prevent the app from being used easily.
I'm curious what causes this and what I can do to fix it. Thank you!

UITextField used for searching UITableView with multiple saved strings

In my app, there is component for sending one message to multiple users at the same time.
I would like to implement it similar to facebook message composing. By using uitextfield with local notifications, I'm able to filter my UITableView like this;
self.searchTextFieldObserver = [[NSNotificationCenter defaultCenter]
addObserverForName:UITextFieldTextDidChangeNotification
object:self.searchTextView
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note) {
if ([self.displayArray count]) {
NSArray *tempUsersArray = nil;
NSArray *tempNonUsersArray = nil;
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"fullName CONTAINS[cd] %#", self.searchTextView.text];
self.displayArray = [MyAddressBook sortedContacts:self.contacts];
if ([self.searchTextView.text length] > 0) {
tempUsersArray = [self.displayArray[0] filteredArrayUsingPredicate:predicate];
self.displayArray = #[tempUsersArray];
}
}
[self.tableView reloadData];
}];
This works as expected... As I'm providing input for textfield, my table gets filtered. What I want to implement is this approach:
When I select one user by searching the table view, his nickname should be inserted in my textfield and predicate should be reseted to empty string, so I can start filtering again. Back button should select already inserted name and on second backspace tap, it should delete it.
I was thinking about this for some time, and all I could come up with, was using multiple element on top of each other. UITextView would change it's frame as users are added up (saved in array, which is source for UILabel's text, that partly replaces frame of textview), but I hitted wall, when I had to have possibility of removing already picked users.
If you guys know about another approach, or about any library that could help me, I would be very glad.
Sorry for making this an answer instead of just a comment, but I don't have enough reputation yet to comment.
Anyway, I think I would probably have an array of the selected user names that have been added to the textField. Then you could use UIControlEventEditingChanged to check for the text changing, and in that method that gets called take the textField's current text, strip out any strings that match those in the selected user names array as well as commas and such, then set your filter string to what's left over.
As an example of how you could use UIControlEventEditingChanged:
[_textField addTarget:self action:#selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
In the case of removing users from the textField, you could use that same textFieldDidChange method to compare the array of added users to the textField, and if one exists in the array that doesn't exist in the textField anymore remove it before re-filtering.
-Stephen

Comparing NSString to UITextField text never gets called

I record the value of the text in my UITextField and I want to compare the text to the original text field value later. I try something like this, but I never get the NSLog to be displayed. Any ideas why?
defaultTopicText = topicTextField.text;
if ([topicTextField.text isEqualToString:defaultTopicText]){
NSLog(#"YES");
}else{
NSLog(topicTextField.text);
NSLog(defaultTopicText);
}
The code looks exactly like you see it. The first line I assign the value and the other - I compare with it. And it's not being called.
EDIT:
The code itself IS getting called and I also get the same values when I put them in NSLog. Might the problem be that the text field contains #"\n" characters?
NSLog gives me this:
2013-03-18 20:45:22.037 myapp[524:907]
Here comes the text
2013-03-18 20:45:22.039 myapp[524:907]
Here comes the text
Try to print out the value of the topicTextField.text and see what is shows. otherwise set the breakpoints to see if you are reaching to that particular line of code.
You coud also try comparing after removing the white spaces and new line, if there might be any
NSString *trimmmedText = [topicTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([trimmmedText isEqualToString:defaultTopicText]){
NSLog(#"YES");
}
Try changing to this:
NSString *newString = [defaultTopicText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([newString isEqualToString:defaultTopicText]){
NSLog(#"YES");
}
I typed the following the figured out the answer...
running this should give you your answer:
if(!defaultTopicText){
NSLog(#"defaultTopicText is nil");
}else{
NSLog(#"defaultTopicText is a: %#".[defaultTopicText classname]);
}
defaultTopicText = topicTextField.text;
if ([topicTextField.text localizedCaseInsensitiveCompare:defaultTopicText] == NSOrderedSame){
NSLog(#"YES");
}else{
NSLog(#"\"%#\" != \"%#\"",defaultTopicText, topicTextField.text);
}
Then I realized: topicTextField.text can only not be the same object as itself using this comparison method if it is nil.
topicTextField.text has to be nil... so it ends up executing:
id var = nil;
[var isEqual:nil];
and the runtime makes that return 0;
... so fix your outlet to topicTextField

Unable to add text from UITextField to an Array

Currently I have a custom view table cell and a text field just above it. I want to get the text from the UItextfield and put that into an NSMutableArray.
Pseudocode:
String text = _textfield.text;
[array addObject:text];
NSLog{array}
In my header file I have created the textfield and the array.
I currently receive the error : 'CustomTableView:[340:11303] array: (null)' when I NSLog.
I am not to sure why the text from the textfield is not getting added to the array. If any one is able to help it will be greatly appreciated.
Note - My textfield is above the custom cell not in it. I have even tried just adding a string to the array directly and logging it and I get the same error. So I would assume that this is something to do with the array.
did you initialize your Array.take a MutableArray and initialize it.
NSMutableArray *array=[NSMutableArray alloc]init];
You mentioned that you have declared the textfield and the array in your header file...
Have you initialised the variable array?
e.g.
array = [NSMutableArray new];
It looks like you are not actually creating the array. In Objective C, you do not create things in header file, you declare them. The implementation files(.m files) do all the work.
Try this:
NSString *text = _textfield.text;
array = #[text]
NSLog( #"%#", array );
This is how you should print your array,
NSLog(#"%#", array);
It looks as if your a newbie to ios.Go through the objective-c and Read the apple documentation carefully.
NSString * text = self.textfield.text;
NSMutableArray *array = [NSMutableArray alloc] init];
[array addObject:text];
NSLog(#"%#",array);
For me this is what worked...
I have taken one textfield inside tableviewcell. I am creating textfields based on dynamic data. My requirement is , I need to get textfields text which are created dynamically.
For getting text in another method
NSIndexPath *indexPath = [tableViewObj indexPathForCell:customCell];
if (indexPath.row==0)
{
[arrayPhoneNumbers addObject:customCell.textFieldObj.text];
NSLog(#"array is :%#",arrayPhoneNumbers);
}
else if(indexPath.row==1)
{
[arrayPhoneNumbers addObject:customCell.textFieldObj.text];
NSLog(#"array is :%#",arrayPhoneNumbers);
}
else if(indexPath.row==2)
{
[arrayPhoneNumbers addObject:customCell.textFieldObj.text];
NSLog(#"array is :%#",arrayPhoneNumbers);
}
Like this I have added textfield text to array. Let me know if you have any doubts.

Resources