I am programmatically changing the title of a UIButton to display count of items in a NSMutableArray.
Sometimes, the title does not update as I add items to the array. When I do the NSLog of what the title should be, it is correct but the button title does not update all the time.
Can anyone spot a problem with my code?
- (void) refreshAfterBlueToothScan
{
/*************************************Refresh Displayed Total********************/
//[_manualBCtemporaryCartArray26 removeAllObjects];
//_manualBCtemporaryCartArray26 = [[NSMutableArray alloc] init];
[localTempArray removeAllObjects];
if (!localTempArray)
{
localTempArray = [[NSMutableArray alloc] init];
}
// Get the DBAccess object;
DBAccess *dbAccess1 = [[DBAccess alloc] init];
// Get the products array from the database
//Get the latest NSMutableArray
localTempArray = [dbAccess1 getProductsFromTmpSales];
// Close the database because we are finished with it
[dbAccess1 closeDatabase];
//Count How many products in array
int iNumberofArrayProducts;
iNumberofArrayProducts = [localTempArray count];
NSString* productCount = [NSString stringWithFormat:#"%i", iNumberofArrayProducts];
NSLog(#"The NUMBER OF TmpTable PRODUCTS is %#",productCount);
//Sum the selling price of the records in the _manualBCtemporaryCartArray26
amountSum = [localTempArray valueForKeyPath:#"#sum.lTotalSellingPrice"];
NSLog(#"The total TmpTable SELLING PRICE is %#",amountSum);
NSNumberFormatter * formatter = [[NSNumberFormatter alloc]init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2]; // Set this if you need 2 digits
[formatter setMinimumFractionDigits:2]; // Set this if you need 2 digits
NSString * newString = [formatter stringFromNumber:[NSNumber numberWithFloat:[amountSum floatValue]]];
NSLog(#"FORMATTED MONTHLY SALES IS,R%#",newString);
//This is a hack that replaces the comma with a dot. I want to display the Price as R2 000.10
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:#"/:,"];
newString=[[newString componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: #"."];
NSString *item = [NSString stringWithFormat:#"R%# (%i)",newString, iNumberofArrayProducts];
/**********Play audio to warn user that item was added to cart*******/
// ivar
SystemSoundID mBeep;
// Create the sound ID
NSString* path = [[NSBundle mainBundle]
pathForResource:#"scanBarCode" ofType:#"mp3"];
NSURL* url = [NSURL fileURLWithPath:path];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &mBeep);
// Play the sound
AudioServicesPlaySystemSound(mBeep);
// Dispose of the sound
//AudioServicesDisposeSystemSoundID(mBeep);
/**********END - Play audio to warn user that item was added to cart*******/
//When user scans the barcode, we want to display the product that was just scanned. This allows user to see what product they just scanned as it is automatically loaded on the shopping cart. Put IF Statement so this code only executes after the scanning barcode.
[self.searchDisplayController setActive: YES animated: YES];
//self.searchDisplayController.searchBar.hidden = NO;
self.searchDisplayController.searchBar.text = [NSString stringWithFormat:#"%i",fklInventoryID];
[self.searchDisplayController.searchBar becomeFirstResponder];
[self.searchDisplayController.searchBar resignFirstResponder];
NSLog(#"BUTTON ITEM IS,%#",item);
[manualTotalPriceBtn setTitle: item forState: UIControlStateNormal];
/*************************************END - Refresh Displayed Total********************/
}
Try this:
[manualTotalPriceBtn setAttributedTitle:nil forState:UIControlStateNormal];
[manualTotalPriceBtn setTitle:item forState:UIControlStateNormal];
If you are using a xib file the IB will set your value for the attributedTitle instead of the title.
try changing button type from system to custom.
Check that you update the button on the mainthread. If your method is called from a callback of whatever bluetooth scanner module you are using, it might be happening on a backround thread. This will cause button to sometimes update, sometimes it will not, or later.
If not, check the superview property of the button to not be nil. Maybe somewhere in your code you create a bew button, add it to the superview but forgot update your property to point to it (or some other scenario where you update a button that is not inserted in the view).
Related
I'm saving the textfields data in SQLite when click the save button. Now I want to show that data in button text. I'm getting data from SQLite in an NSMutableArray, but when I set the titleLabel of button it does not appear there. How can I get the array data in button text. My code to get data from SQLite is this:
- (IBAction)btnShow:(id)sender {
NSString *show=[[NSString alloc]initWithFormat:#"select * from persondata where id='%#'",_txtID.text];
dboperation *db = [[dboperation alloc]init];
_arrmainData = [[NSMutableArray alloc]init];
_arrmainData=[db getalluser:show];
NSLog(#"Arr %#",_arrmainData);
for (NSDictionary * oneCustomer in _arrmainData){
[oneCustomer objectForKey:#"address"];
NSLog(#"ID: %# ",oneCustomer);
_btnShowData.titleLabel.text = [NSString stringWithFormat:#"%#",oneCustomer];
NSLog(#"XX %#",_btnShowData.titleLabel.text);
}
}
Set the title like this
[_btnShowData setTitle: [NSString stringWithFormat:#"%#", [oneCustomer objectForKey:#"address"]] forState:UIControlStateNormal];
Try to replace
_btnShowData.titleLabel.text = [NSString stringWithFormat:#"%#",oneCustomer];
with
[_btnShowData setTitle:[NSString stringWithFormat:#"%#",oneCustomer] forState:UIControlStateNormal];
I am using a Calendar view in my project. I am using a MBCalendarKit. That time single date in single event show. But I want single date on multiple events show. But how it possible please help.
- (void) viewWillAppear: (BOOL)animated{
NSArray *title = [_caldevice valueForKey:#"pill"];
// NSLog(#"event name fetch %#",title);
NSArray *date =[_caldevice valueForKey:#"datetaken"];
// NSLog(#"event fetch %#",date);
NSArray*dose= [_caldevice valueForKey:#"dose"];
NSString *title1;
NSString*title2;
NSDate *date1;
NSData *imgdata;
CKCalendarEvent *releaseUpdatedCalendarKit;
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"dd-MM-yyyy";
for (int i = 0; i < [date count]; i++){
title1 = NSLocalizedString(title[i], #"");
title2 = NSLocalizedString(dose[i], #"");
NSString *combined = [NSString stringWithFormat:#"%# - %#", title1, title2];
date1 = [dateFormatter dateFromString:date[i]];
releaseUpdatedCalendarKit = [CKCalendarEvent eventWithTitle:combined andDate:date1 andInfo:Nil];
// NSLog(#"Event: %# , %#",combined,date1);
// releaseUpdatedCalendarKit = [CKCalendarEvent eventWithTitle:combined andDate:date1 andInfo:Nil andColor:[UIColor blueColor]];
self.data[date1] = #[releaseUpdatedCalendarKit];
}
}
You're looping over a bunch of events and for each event, you're *replacing the previously assigned array with a new one, containing a single element.
Replace this:
self.data[date1] = #[releaseUpdatedCalendarKit];
with something more like this:
// 1. First, get the previous events for that day.
NSMutableArray <CKCalendarEvent *> *events = self.data[date1].mutableCopy;
// 2. If events exist, append the event, otherwise create an empty array with the new event.
if (events) {
[events addObject: newEvent];
}
else {
events = #[newEvent];
}
// 3. Set the events for the date key.
self.data[date1] = events;
This way you're doing an "add or create" operation, instead of overwriting each time.
Disclosure: I wrote and maintain MBCalendarKit.
I have a global variable in FirstViewController.h
extern NSString *dateString;
it records the date/time of when I press saveText button. There is another button called readText which pushes a UITableView. The first cell on this table will print the date saved.
However, this only works if I first press the saveText button. Otherwise, if I just press readText, it crashes. How can I get it so that if there is no current datetime saved, that it doesn't crash?
Here is where I wrote the timestamp for saveButton:
-(IBAction)saveText:(id)sender{
//code to save text, irrelevant to the question//
dateString = [NSDateFormatter localizedStringFromDate:[NSDate date]
dateStyle:NSDateFormatterShortStyle
timeStyle:NSDateFormatterShortStyle];
NSLog(#"%#",dateString);
}
and here is the code to load the tableviewcells with the timestamp
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *str = #"Text- saved on: ";
str = [str stringByAppendingString: dateString];
self.list = [[NSArray alloc] initWithObjects: str, nil];
}
In my methods that use the variable dateString,
I used:
if([dateString length] == 0){
//perform standard procedure
}
else {
//what I want it to do
}
I have a UITextView in my tableview cell. This is how I assign my NSAttributedString to its content:
- (void)setAttributedMessage:(NSAttributedString *)msg
{
self.bubbleView.textView.text = nil;
self.bubbleView.textView.font = nil;
self.bubbleView.textView.textColor = nil;
self.bubbleView.textView.textAlignment = NSTextAlignmentLeft;
self.bubbleView.textView.attributedText = msg;
self.bubbleView.textView.userInteractionEnabled = NO;
}
And my attributed string contains a message text and a date in smaller font by it, so it's how I create it:
- (NSAttributedString *) attributedTextForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *txt = #"Some text";
NSMutableAttributedString *a = [[NSMutableAttributedString alloc] initWithString:txt attributes:#{NSFontAttributeName: [UIFont systemFontOfSize:16]}];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.timeStyle = NSDateFormatterShortStyle;
df.dateStyle = NSDateFormatterNoStyle;
NSString *timestamp = [df stringFromDate:[NSDate date]];
[a appendAttributedString:[[NSAttributedString alloc]
initWithString:[NSString stringWithFormat:#" %#", timestamp]
attributes:#{NSFontAttributeName: [UIFont italicSystemFontOfSize:10]}]];
return [[NSAttributedString alloc] initWithAttributedString:a];
}
What I'm getting, when displaying the Table View, is a plain text - no change of font size or no italics with date. When the cell is redisplayed though it gets displayed properly. So When I scroll the cell out of the screen and get it back there, it's OK. I could also reload the table view to force re-displaying, but this solution sounds like a really lame one.
Any idea what's going on there?
You may not like it, but the best solution is really the "lame" one:
[yourTableView reloadData];
That way, new views will be generated for all (visible) entries, especially the on-screen ones.
Here was my solution:
this forces the label to update on the next operation cycle (I imagine it needs to do some sort of setup in the first instance)
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[cell.label setAttributedText:cellString];
}];
I fixed it by setting table data in viewDidLoad and then refreshing my table view inside viewDidAppear method.
after a lot of searching and still searching, i'm unable to find the way to extract the slides out of powerpoint presentations. Need help, if they know anything related this or have implemented such thing, source code will be great or any reference link will also work. I have been using QLPreviewController, but i failed to override it.
I am not sure whether this is still required. but anyways, this is how I have implemented
(1) Use UIWebView to display the content of the PPT. The well formed (!) HTML allows you to parse it. Get the html using
NSString *htmlContent = [self.webView stringByEvaluatingJavaScriptFromString:#"document.body.innerHTML"];
(2) Count the number of div class = 'slide to get the slide count
(4) You need to parse the HTML to get the styles and div using the below code
(5) Get all the styles
- (NSString *)getStyles:(int)slideCount forView:(UIWebView *)view {
NSString *getElementByTag = [[NSString alloc] init];
NSString *allStyles = [[NSString alloc] init];
for (int i = 0; i < slideCount; i++) {
getElementByTag = [NSString stringWithFormat:#"document.getElementsByTagName('style')[%d].innerHTML", i];
NSString *style = [[view stringByEvaluatingJavaScriptFromString:getElementByTag] stringByAppendingString:#"\n"];
allStyles = [allStyles stringByAppendingString:style];
}
allStyles = [#"<style type='text/css'>" stringByAppendingString: allStyles];
return [allStyles stringByAppendingString:#"</style>"];
}
(6) Concatenate all the styles from step 5 with div tag content. Define a NSMutableArray variable to to store all slides with styles for future reference. Define NSMutableArray *slides to store all the slides
- (void)makeSlides:(int)slideCount forView:(UIWebView *)view {
self.slides = [[NSMutableArray alloc] init];
for (int i = 0; i < slideCount; i++) {
NSString *slideBody = [NSString stringWithFormat:#"document.getElementsByClassName('slide')[%d].innerHTML", i];
NSString *div = [view stringByEvaluatingJavaScriptFromString:slideBody];
NSString *slide = [self.slideStyles stringByAppendingString:div];
[self.slides addObject:slide];
}
}
Hope this helps