UITextField Strange issue while setting Font - ios

I'm trying to set the font of UITextField programatically. The issue is that it works in a strange manner.
I have multiple UITextFields in a UITableViewController.
I tried setting the font this way
[self.textfieldProspect setFont:nil];
[self.textfieldProspect setFont:[UIFont systemFontOfSize:15]];
I put the above code in ViewDidLoad, ViewWillAppear and ViewDidLayoutSubviews.
It only works in ViewDidLayoutSubviews. Which causes the textField to change it's font visibly once the view controller becomes visible. I do not want that, I would like the font to be set before the ViewController becomes visible.
I present the viewController modally.
Is there anyway to change font before the textField becomes visible. It sounds like a trivial question, but I tried everything and nothing seems to work.
Here is the complete code
#import <UIKit/UIKit.h>
#protocol AddActivityViewControllerDelegate;
#interface AddActivityViewController : UITableViewController
#end
- (void)viewDidLoad
{
[super viewDidLoad];
self.themeManager = [ThemeManager sharedThemeManager];
[self.themeManager applyAppBackgroundColorToView:self.view];
self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
self.textviewNotes.text = #"";
self.textviewNotes.placeholder = #"Notes";
self.textviewNotes.placeholderColor = [CommonHelper getSelectedVarientPlaceHolderColor];
[self setUpTextFieldsPaddingView];
self.dateFormatter = [CommonHelper getDateFormatterWithFormat:#"MMM d, yyyy h:mm a"];
UIToolbar *toolbar = [[UIToolbar alloc] init];
[toolbar setBarStyle:UIBarStyleBlackTranslucent];
[toolbar sizeToFit];
UIBarButtonItem* doneButton =[[UIBarButtonItem alloc] initWithTitle:#"Done" style:UIBarButtonItemStyleDone target:self action:#selector(resignKeyboardCustom:)];
NSArray *itemsArray = [NSArray arrayWithObjects:doneButton,nil];
[toolbar setItems:itemsArray animated:NO];
[self.fieldEndDate setInputAccessoryView:toolbar];
[self.fieldStartDate setInputAccessoryView:toolbar];
self.datePicker = [[UIDatePicker alloc] init];
self.datePicker.datePickerMode = UIDatePickerModeDateAndTime;
//self.datePicker.minimumDate = [NSDate date];
[self.datePicker addTarget:self action:#selector(datePickerValueChanged:) forControlEvents:UIControlEventValueChanged];
self.fieldStartDate.inputView = self.datePicker;
self.fieldEndDate.inputView = self.datePicker;
UIView* seperatorView = [[UIView alloc] initWithFrame:CGRectMake(0, 43, self.navigationController.navigationBar.frame.size.width, 1)];
seperatorView.backgroundColor = [UIColor lightGrayColor];
[self.navigationController.navigationBar addSubview:seperatorView];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0,0,64,30);
[btn setBackgroundColor:[UIColor darkGrayColor]];
[btn setTitle:#"Cancel" forState:UIControlStateNormal];
btn.titleLabel.font = [self.themeManager getSelectedFont];
[btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[btn addTarget:self action:#selector(hideViewController) forControlEvents:UIControlEventTouchUpInside];
btn.layer.cornerRadius = 3.0f;
UIBarButtonItem *barBackBtn = [[UIBarButtonItem alloc] initWithCustomView:btn];
btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0,0,64,30);
[btn setBackgroundColor:[UIColor darkGrayColor]];
[btn setTitle:#"Done" forState:UIControlStateNormal];
btn.titleLabel.font = [self.themeManager getSelectedFont];
[btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[btn addTarget:self action:#selector(doneButtonTapped) forControlEvents:UIControlEventTouchUpInside];
btn.layer.cornerRadius = 3.0f;
UIBarButtonItem *barDoneBtn = [[UIBarButtonItem alloc] initWithCustomView:btn];
self.navigationItem.rightBarButtonItem = barDoneBtn;
self.navigationItem.leftBarButtonItem = barBackBtn;
//Data Models
///////////////////////////////////////////////////////////////////
Up_DateAppDelegate* appDelegate = (Up_DateAppDelegate*)[UIApplication sharedApplication].delegate;
self.managedObjectContext = appDelegate.managedObjectContext;
self.prospect = [appDelegate GetSelectedProspect];
NSLog(#"nickname%#",self.prospect.nickName);
NSLog(#"firstname%# ",self.prospect.firstName);
NSLog(#"lastname %#",self.prospect.lastName);
self.btnDeleteActivity.hidden = YES;
self.selectedStartDate = [NSDate date];
isStartDateSelected = YES;
self.fieldStartDate.text = [self.dateFormatter stringFromDate:self.selectedStartDate];
if (self.isCalendarMode == YES)
{
NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults synchronize];
NSDate* startDate = [userDefaults objectForKey:#"CurrentSelectedMonthForCalendar"];
//Getting current time
NSDate* currentTime = [NSDate date];
NSCalendar* theCalendar = [NSCalendar currentCalendar];
NSDateComponents *dayComponent = [theCalendar components:( NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond ) fromDate:startDate];
//[dayComponent setTimeZone:[NSTimeZone defaultTimeZone]];
NSDateComponents* timeComponents = [theCalendar components:(NSCalendarUnitHour) fromDate:currentTime];
[dayComponent setHour:timeComponents.hour];
[dayComponent setMinute:0];
[dayComponent setSecond:0];
startDate = [theCalendar dateFromComponents:dayComponent];
self.initiallySelectedDateForCalendarMode = startDate;
self.selectedStartDate = startDate;
self.fieldStartDate.text = [self.dateFormatter stringFromDate:startDate];
//Autocomplete Search options for prospects
activityProspectsAutocompleteVC = [ActivityProspectsAutocompleteViewController createAndSetupAutoCompleteWithDisplayViewController:self textfield:self.textfieldProspect];
[self.view addSubview:tableviewAutoCompleteProspects];
}
self.fieldEndDate.text = #"";
self.resultLevelSelected = #"None";
self.repeatCountSelected = 0;
self.repeatOptionSelected = #"Never";
self.alertOptionSelected = #"None";
[self.timeInvestmentLabel setFont:[UIFont fontWithName:[CommonHelper getBoldFontForFontName:[self.themeManager getSelectedFontName]] size:[self.themeManager getBiggerFontSize]]];
[self.timeInvestmentLabel setTextColor:[UIColor whiteColor]];
[self.resultLabel setFont:[UIFont fontWithName:[CommonHelper getBoldFontForFontName:[self.themeManager getSelectedFontName]] size:[self.themeManager getBiggerFontSize]]];
[self.resultLabel setTextColor:[UIColor whiteColor]];
self.timeInvestmentLabel.attributedText = [[NSAttributedString alloc] initWithString:#"Time Investment" attributes:#{ NSStrokeColorAttributeName : [UIColor blackColor], NSForegroundColorAttributeName : [UIColor whiteColor], NSStrokeWidthAttributeName : #-3.5}];
self.resultLabel.attributedText = [[NSAttributedString alloc] initWithString:#"Result?" attributes:#{ NSStrokeColorAttributeName : [UIColor blackColor], NSForegroundColorAttributeName : [UIColor whiteColor], NSStrokeWidthAttributeName : #-3.5}];
NSAttributedString *attributedText =
[[NSAttributedString alloc] initWithString:#" Result"
attributes:#{NSStrokeWidthAttributeName: [NSNumber numberWithInt:-3],
NSStrokeColorAttributeName: [UIColor lightGrayColor],
NSForegroundColorAttributeName: [UIColor whiteColor]}];
[self.btnResultLevel setAttributedTitle:attributedText forState:UIControlStateNormal];
if (self.isCalendarMode == NO)
{
//coming from prospect
self.textfieldProspect.userInteractionEnabled = NO;
}
NSString* pageTitle = #"";
if (self.editModeEnabled == NO)
{
//Add Activity for a Pospect
self.textfieldProspect.text = [CommonHelper getDisplayNameForProspec:self.prospect];
[self.textfieldProspect setFont:nil];
[self.textfieldProspect setFont:[self.themeManager getSelectedBiggerFont]];
if (self.isCalendarMode == YES)
{
self.textfieldProspect.text = #"";
[self.textfieldProspect setFont:nil];
[self.textfieldProspect setFont:[self.themeManager getSelectedBiggerFont]];
}
pageTitle = #"Add Activity";
}
else
{
//Edit Mode
[self setUpFieldsValuesFromDataModel];
pageTitle = #"Edit Activity";
}
// Creating custom title view so that we can apply font of our choice
CGRect frame = CGRectMake(0, 0, 200, 21);
UILabel *label = [[UILabel alloc] initWithFrame:frame];
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont fontWithName:[CommonHelper getBoldFontForFontName:[self.themeManager getSelectedFontName]] size:[self.themeManager getBiggerFontSize]];
label.textAlignment = NSTextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.text = pageTitle;
self.navigationItem.titleView = label;
//Delete Activity button
[self.btnDeleteActivity.layer setShadowColor:[UIColor blackColor].CGColor];
[self.btnDeleteActivity.layer setShadowOpacity:1.0];
[self.btnDeleteActivity.layer setShadowRadius:3.0];
[self.btnDeleteActivity.layer setShadowOffset:CGSizeMake(0,3.0)];
self.btnDeleteActivity.layer.masksToBounds = NO;
self.btnDeleteActivity.layer.cornerRadius = 3.0f;
}
-(void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
[self.textfieldProspect setFont:nil];
[self.textfieldProspect setFont:[self.themeManager getSelectedBiggerFont]];
[self.textfieldActivity setFont:nil];
[self.textfieldActivity setFont:[self.themeManager getSelectedBiggerFont]];
[self.textfieldLocation setFont:nil];
[self.textfieldLocation setFont:[self.themeManager getSelectedBiggerFont]];
[self.textfieldWebsite setFont:nil];
[self.textfieldWebsite setFont:[self.themeManager getSelectedBiggerFont]];
[self.fieldEndDate setFont:nil];
[self.fieldEndDate setFont:[self.themeManager getSelectedBiggerFont]];
[self.fieldStartDate setFont:nil];
[self.fieldStartDate setFont:[self.themeManager getSelectedBiggerFont]];
[self.textfieldMonetaryInvestment setFont:nil];
[self.textfieldMonetaryInvestment setFont:[self.themeManager getSelectedBiggerFont]];
}

Related

when i am using 3 view on viewcontroller it get slow in objective c

I am using 3 view on one UIViewController. Because of this I have lots of code in viewDidLoad() Like this:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
customActivityIndicator.animationImages = [NSArray arrayWithObjects:[UIImage imageNamed:#"tmp-0.gif"],[UIImage imageNamed:#"tmp-1.gif"],[UIImage imageNamed:#"tmp-2.gif"],[UIImage imageNamed:#"tmp-3.gif"],[UIImage imageNamed:#"tmp-4.gif"],[UIImage imageNamed:#"tmp-5.gif"],[UIImage imageNamed:#"tmp-6.gif"],[UIImage imageNamed:#"tmp-7.gif"],[UIImage imageNamed:#"tmp-8.gif"],[UIImage imageNamed:#"tmp-9.gif"],[UIImage imageNamed:#"tmp-10.gif"],[UIImage imageNamed:#"tmp-11.gif"],[UIImage imageNamed:#"tmp-12.gif"],[UIImage imageNamed:#"tmp-13.gif"],[UIImage imageNamed:#"tmp-14.gif"],[UIImage imageNamed:#"tmp-15.gif"],nil];
customActivityIndicator.animationDuration = 1.0; // in seconds
customActivityIndicator.animationRepeatCount = 0; // sets to loop
[customActivityIndicator startAnimating];
btn.hidden=YES;
UILabel *lab =[[UILabel alloc] init];
lab.text = [NSString awesomeIcon:FaMailReply];
UIImage *listImage2 = [UIImage imageNamed:#"backicon.png.png"];
UIButton *listButton2 = [UIButton buttonWithType:UIButtonTypeCustom];
listButton2.backgroundColor=[UIColor whiteColor];
[[listButton2 layer] setBorderWidth:0.5f];
listButton2.layer.borderColor =[[UIColor blackColor] CGColor];
listButton2.layer.cornerRadius = btn.bounds.size.width / 3.4;// this value vary as per your desire
listButton2.clipsToBounds = YES;
UIFont *font = [UIFont fontWithName:#"FontAwesome" size:15.0];
UIColor *color = [UIColor blueColor];
NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName,color,NSForegroundColorAttributeName, nil];
// [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName,color,NSForegroundColorAttributeName, nil];
NSAttributedString *attributedStr = [[NSAttributedString alloc] initWithString:lab.text attributes:attrsDictionary];
// get the image size and apply it to the button frame
CGRect listButton2Frame = listButton2.frame;
listButton2Frame.size = listImage2.size;
listButton2.frame = listButton2Frame;
[listButton2 setAttributedTitle:attributedStr forState:UIControlStateNormal];
[listButton2 addTarget:self
action:#selector(LogoutClick:)
forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *jobsButton2 =
[[UIBarButtonItem alloc] initWithCustomView:listButton2];
//Notificaation Icon Button...
UILabel *lablnotification =[[UILabel alloc] init];
// lab.font = [UIFont fontWithName:#"FontAwesome" size:8];
// lab.textColor = [UIColor whiteColor];
lablnotification.text = [NSString awesomeIcon:FaHome];
UIImage *listImage4 = [UIImage imageNamed:#"notification.png"];
UIButton *listButton4 = [UIButton buttonWithType:UIButtonTypeCustom];
listButton4.backgroundColor=[UIColor whiteColor];
[[listButton4 layer] setBorderWidth:0.5f];
listButton4.layer.borderColor =[[UIColor blackColor] CGColor];
listButton4.layer.cornerRadius = btn.bounds.size.width / 3.4;// this value vary as per your desire
listButton4.clipsToBounds = YES;
UIFont *fontnotification = [UIFont fontWithName:#"FontAwesome" size:18.0];
UIColor *colornotification = [UIColor blueColor];
NSDictionary *attrsDictionarynotification = [NSDictionary dictionaryWithObjectsAndKeys:fontnotification,NSFontAttributeName,colornotification,NSForegroundColorAttributeName, nil];
// [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName,color,NSForegroundColorAttributeName, nil];
NSAttributedString *attributedStrnotification = [[NSAttributedString alloc] initWithString:lablnotification.text attributes:attrsDictionarynotification];
// get the image size and apply it to the button frame
CGRect listButton4Frame = listButton4.frame;
listButton4Frame.size = listImage4.size;
listButton4.frame = listButton4Frame;
[listButton4 setAttributedTitle:attributedStrnotification forState:UIControlStateNormal];
[listButton4 addTarget:self
action:#selector(ActualNotificationClick:)
forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *jobsButton4 =
[[UIBarButtonItem alloc] initWithCustomView:listButton4];
UIImage *listImage3 = [UIImage imageNamed:#"ec2.png"];
UIButton *listButton3 = [UIButton buttonWithType:UIButtonTypeCustom];
// get the image size and apply it to the button frame
CGRect listButton3Frame = listButton3.frame;
listButton3Frame.size = listImage3.size;
listButton3.frame = listButton3Frame;
[listButton3 setImage:listImage3 forState:UIControlStateNormal];
[listButton3 addTarget:self
action:#selector(EmployeeClick:)
forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *jobsButton3 =
[[UIBarButtonItem alloc] initWithCustomView:listButton3];
self.navigationItem.rightBarButtonItems= [NSArray arrayWithObjects:jobsButton2,jobsButton4, nil];
self.navigationItem.leftBarButtonItems=[NSArray arrayWithObjects:jobsButton3, nil];
//NSUserDefault...
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
userid = [defaults objectForKey:#"UserId"];
NSLog(#"User Id is =%#",userid);
ServerString=[defaults objectForKey:#"ServerString"];
DefaultRegionIDString=[defaults objectForKey:#"DefaultRegionIDString"];
DefaultBranchIDString=[defaults objectForKey:#"DefaultBranchIDString"];
DefaultSiteIDString=[defaults objectForKey:#"DefaultSiteIDString"];
DefaultLocationString=[defaults objectForKey:#"DefaultLocationString"];
DefaultDateString =[defaults objectForKey:#"DefaultDateString"];
DefaultTimeString =[defaults objectForKey:#"DefaultTimeString"];
DefaultEmployeeNameString=[defaults objectForKey:#"DefaultEmployeeNameString"];
DefaultRegionNameString=[defaults objectForKey:#"DefaultRegionNameString"];
DefaultBranchNameString=[defaults objectForKey:#"DefaultBranchNameString"];
DefaultSiteNameString=[defaults objectForKey:#"DefaultSiteNameString"];
DefaultEventTypeString=[defaults objectForKey:#"DefaultEventTypeString"];
DefaultIncidentTypeString=[defaults objectForKey:#"DefaultIncidentTypeString"];
DefaultsIncidentNameString=[defaults objectForKey:#"DefaultsIncidentNameString"];
SegmentStringCheck=[defaults objectForKey:#"SegmentStringCheck"];
CheckIncidentString=[defaults objectForKey:#"CheckIncidentString"];
if([DefaultEventTypeString isEqualToString:#"1"])
{
lblreportregion.text = DefaultRegionIDString;
lblreportbranch.text = DefaultBranchIDString;
lblreportsite.text = DefaultSiteIDString;
// lblreportinjurytype.text=DefaultIncidentTypeString;
txtreportlocation.text = DefaultLocationString;
txtreportdate.text = DefaultDateString;
txtreporttime.text = DefaultTimeString;
txtreportemp.text = DefaultEmployeeNameString;
txtreportregion.text=DefaultRegionNameString;
txtreportbranch.text=DefaultBranchNameString;
txtreportsite.text=DefaultSiteNameString;
// txtreportinjurytype.text = DefaultsIncidentNameString;
}
else if ([DefaultEventTypeString isEqualToString:#"2"])
{
lblnearregion.text = DefaultRegionIDString;
lblnearbranch.text = DefaultBranchIDString;
lblnearsite.text = DefaultSiteIDString;
txtnearlocation.text = DefaultLocationString;
txtneardate.text = DefaultDateString;
txtneartime.text = DefaultTimeString;
txtnearemp.text = DefaultEmployeeNameString;
txtnearregion.text=DefaultRegionNameString;
txtnearbranch.text=DefaultBranchNameString;
txtnearsite.text=DefaultSiteNameString;
}
else if ([DefaultEventTypeString isEqualToString:#"3"])
{
lblspotingregion.text = DefaultRegionIDString;
lblspotingbranch.text = DefaultBranchIDString;
lblspotingsite.text = DefaultSiteIDString;
txtspotinglocation.text = DefaultLocationString;
txtspotingdate.text = DefaultDateString;
txtspotingtime.text = DefaultTimeString;
txtsportingemp.text = DefaultEmployeeNameString;
txtspotingregion.text=DefaultRegionNameString;
txtspotingbranch.text=DefaultBranchNameString;
txtspotingsite.text=DefaultSiteNameString;
}
if([SegmentStringCheck isEqualToString:#"0"])
{
segment.selectedSegmentIndex = UISegmentedControlNoSegment;
segment.selectedSegmentIndex = 0;
viewspoting.hidden=NO;
viewnear.hidden=YES;
viewreport.hidden=YES;
}
else if ([SegmentStringCheck isEqualToString:#"1"])
{
segment.selectedSegmentIndex = UISegmentedControlNoSegment;
segment.selectedSegmentIndex = 1;
viewspoting.hidden=YES;
viewnear.hidden=NO;
viewreport.hidden=YES;
//Near...
[self nearserverconnection];
[self nearserverconnectionincident];
[self nearserverconnectionactivity];
}
else if ([SegmentStringCheck isEqualToString:#"2"])
{
segment.selectedSegmentIndex = UISegmentedControlNoSegment;
segment.selectedSegmentIndex = 2;
viewspoting.hidden=YES;
viewnear.hidden=YES;
viewreport.hidden=NO;
//Report...
[self reportserverconnection];
[self reportserverconnectioninjury];
}
else
{
segment.selectedSegmentIndex = UISegmentedControlNoSegment;
segment.selectedSegmentIndex = 0;
viewspoting.hidden=NO;
viewnear.hidden=YES;
viewreport.hidden=YES;
}
//.........................//
//Sporting Hide Code...
//Table...
tablesportingbranch.hidden=YES;
tablesportingregion.hidden=YES;
tablesportingsite.hidden=YES;
//Label...
lblsportingactivitytype.hidden=YES;
lblsportingdept.hidden=YES;
lblsportingemp.hidden=YES;
lblspotingbranch.hidden=YES;
lblspotingincidenttype.hidden=YES;
lblspotingregion.hidden=YES;
lblspotingsite.hidden=YES;
//TextFieldDelegate...
txtspotingsite.delegate=self;
txtsportingemp.delegate=self;
txtspotinglocation.delegate=self;
//Date Picker...
pickerspotingdate.hidden=YES;
pickerspotingtime.hidden=YES;
//............................//
//Near Hide Code...
//View...
// viewnear.hidden=YES;
//Table...
tablenearbranch.hidden=YES;
tablenearregion.hidden=YES;
tablenearsite.hidden=YES;
//Label...
lblnearactivitytype.hidden=YES;
lblnearbranch.hidden=YES;
lblneardept.hidden=YES;
lblnearemp.hidden=YES;
lblnearincidenttype.hidden=YES;
lblnearregion.hidden=YES;
lblnearsite.hidden=YES;
//TextFieldDelegate..
txtnearsite.delegate=self;
txtnearemp.delegate=self;
txtnearlocation.delegate=self;
//Date Picker...
pickerneardate.hidden=YES;
pickerneartime.hidden=YES;
//...........................//
//Report Hide View Code...
//View...
// viewreport.hidden=YES;
//Table...
tablereportbranch.hidden=YES;
tablereportinjurytype.hidden=YES;
tablereportregion.hidden=YES;
tablereportsite.hidden=YES;
//Label...
lblreportbranch.hidden=YES;
lblreportdept.hidden=YES;
lblreportemp.hidden=YES;
lblreportinjurytype.hidden=YES;
lblreportregion.hidden=YES;
lblreportsite.hidden=YES;
//TextFieldDelegate...
txtreportsite.delegate=self;
txtreportemp.delegate=self;
txtreportlocation.delegate=self;
//Date Picker...
pickerreporttime.hidden=YES;
pickereportdate.hidden=YES;
//.............................//
//Font Asowme
//Show...
lblspotingShow.font = [UIFont fontWithName:#"FontAwesome" size:15];
lblspotingShow.textColor = [UIColor blackColor];
lblspotingShow.text = [NSString awesomeIcon:FaEye];
//Scroll View...
[scrollspoting setContentSize:CGSizeMake(300, 500)];
[scrollnear setContentSize:CGSizeMake(300, 500)];
[scrollreport setContentSize:CGSizeMake(300, 730)];
UISwipeGestureRecognizer *gestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(swipeHandler:)];
[gestureRecognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
[self.view addGestureRecognizer:gestureRecognizer];
//Button Diamiter...
//Spoting Button...
btnsportinghideadd.layer.cornerRadius = 4; // this value vary as per your desire
btnsportinghideadd.clipsToBounds = YES;
//Near Button...
btnnearhideadd.layer.cornerRadius = 4; // this value vary as per your desire
btnnearhideadd.clipsToBounds = YES;
//Report Button...
btnreportnext.layer.cornerRadius = 4; // this value vary as per your desire
btnreportnext.clipsToBounds = YES;
//Spoting...
[self spotingserverconnection];
[self spotingserverconnectionactivity];
[self spotingserverconnectionincident];
[txtspotingsite addTarget:self action:#selector(spotingtextFieldDidChangeSite:) forControlEvents:UIControlEventEditingChanged];
// prevents the scroll view from swallowing up the touch event of child buttons
[txtnearsite addTarget:self action:#selector(neartextFieldDidChangeSite:) forControlEvents:UIControlEventEditingChanged];
[txtreportsite addTarget:self action:#selector(reporttextFieldDidChangeSite:) forControlEvents:UIControlEventEditingChanged];
UITapGestureRecognizer *tapGesturereportinjury = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(hideSubViewreportinjury)];
// prevents the scroll view from swallowing up the touch event of child buttons
tapGesturereportinjury.cancelsTouchesInView = NO;
[scrollreport addGestureRecognizer:tapGesturereportinjury];
IssueSelectedIDarray=[[NSMutableArray alloc] init];
IssueSelectedNamearray=[[NSMutableArray alloc] init];
ReportInjurySelectedNamearray=[[NSMutableArray alloc] init];
ReportInjurySelectedIDarray=[[NSMutableArray alloc] init];
[self testInternetConnection];
//Spoting Date and Time..
NSDateFormatter *Spotingdateformatter;
Spotingdateformatter = [[NSDateFormatter alloc] init];
[Spotingdateformatter setDateFormat:#"dd/MM/yyyy"];
SpotingdateString = [Spotingdateformatter stringFromDate:[NSDate date]];
NSLog(#"Current Time =%#",SpotingdateString);
CurrentDate=SpotingdateString;
NSDate * now = [NSDate date];
NSDateFormatter *Spotingtimeformatter = [[NSDateFormatter alloc] init];
[Spotingtimeformatter setDateFormat:#"hh:mm"];
SpotingTimeString = [Spotingtimeformatter stringFromDate:now];
NSLog(#"newDateString %#", SpotingTimeString);
//Near Date and Time..
NSDateFormatter *Neardateformatter;
Neardateformatter = [[NSDateFormatter alloc] init];
[Neardateformatter setDateFormat:#"dd/MM/yyyy"];
NeardateString = [Neardateformatter stringFromDate:[NSDate date]];
NSLog(#"Current Time =%#",NeardateString);
NSDate * nowNear = [NSDate date];
NSDateFormatter *Neartimeformatter = [[NSDateFormatter alloc] init];
[Neartimeformatter setDateFormat:#"hh:mm"];
NearTimeString = [Neartimeformatter stringFromDate:nowNear];
NSLog(#"newDateString %#", NearTimeString);
//Report Date and Time..
NSDateFormatter *Reportdateformatter;
Reportdateformatter = [[NSDateFormatter alloc] init];
[Reportdateformatter setDateFormat:#"dd/MM/yyyy"];
ReportdateString = [Reportdateformatter stringFromDate:[NSDate date]];
NSLog(#"Current Time =%#",ReportdateString);
NSDate * nowReport = [NSDate date];
NSDateFormatter *Reporttimeformatter = [[NSDateFormatter alloc] init];
[Reporttimeformatter setDateFormat:#"hh:mm"];
ReportTimeString = [Reporttimeformatter stringFromDate:nowReport];
NSLog(#"newDateString %#", ReportTimeString);
}
Its working to much slow. Is there is any way to speed it up?
ViewName *Incedent =[[ViewName alloc] initWithNibName:#"ViewName" bundle:nil];
[self.navigationController pushViewController:Incedent animated:YES];
I have used this code to pushviewcontroller.
You need to evaluate what your code is doing, and find out where it is slow. I don't know what this method is doing, but I'm betting the line:
[self testInternetConnection];
is one of the problems. Comment out that line, and see what happens.

Content not displaying on UITableViewCell

I am attempting to create an autosizing cell using PureLayout, however even though all the JSON loads and is correctly assigned to the UITableViewCell objects no data is displayed.
Here is how I am attempting to setup the cell in my Custom TableViewCell Class:
self.backgroundColor = [UIColor whiteColor];
self.accessoryType = UITableViewCellAccessoryNone;
self.accessoryView = nil;
self.selectionStyle = UITableViewCellSelectionStyleNone;
// Fix for contentView constraint warning
[self.contentView setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
// Create ProfileImageView
self.profilePicture = [[UIImageView alloc] initWithFrame:CGRectZero];
self.profilePicture.translatesAutoresizingMaskIntoConstraints = NO;
self.profilePicture.contentMode = UIViewContentModeScaleAspectFill;
self.profilePicture.backgroundColor = [UIColor whiteColor];
[self.contentView addSubview:self.profilePicture];
// Name label
self.nameLabel = [[UILabel alloc] initWithFrame:CGRectZero];
self.nameLabel.translatesAutoresizingMaskIntoConstraints = NO;
self.nameLabel.font = [UIFont fontWithName:#"HelveticaNeue-Medium" size:16];
self.nameLabel.textColor = [UIColor blackColor];
self.nameLabel.numberOfLines = 1;
[self.contentView addSubview:self.nameLabel];
// Username label
self.usernameLabel = [[UILabel alloc] initWithFrame:CGRectZero];
self.usernameLabel.translatesAutoresizingMaskIntoConstraints = NO;
self.usernameLabel.font = [UIFont fontWithName:#"HelveticaNeue-Light" size:14];
self.usernameLabel.textColor = [UIColor darkGrayColor];
self.usernameLabel.numberOfLines = 1;
[self.contentView addSubview:self.usernameLabel];
// Tweet label
self.tweetLabel = [[UILabel alloc] initWithFrame:CGRectZero];
self.tweetLabel.userInteractionEnabled = YES;
self.tweetLabel.translatesAutoresizingMaskIntoConstraints = NO;
self.tweetLabel.numberOfLines = 0; // Must be set for multi-line label to work
self.tweetLabel.lineBreakMode = NSLineBreakByWordWrapping;
self.tweetLabel.font = [UIFont fontWithName:#"HelveticaNeue" size:14];
self.tweetLabel.textColor = [UIColor darkGrayColor];
[self.contentView addSubview:self.tweetLabel];
// Favorite Button
self.favoriteButton = [[DOFavoriteButton alloc] initWithFrame:CGRectZero image:[UIImage imageNamed:#"star.png"] imageFrame:CGRectMake(0, 0, 15, 15)];
[self.contentView addSubview:self.favoriteButton];
// Retweet Button
self.retweetButton = [[DOFavoriteButton alloc] initWithFrame:CGRectZero image:[UIImage imageNamed:#"retweet.png"] imageFrame:CGRectMake(0, 0, 15, 15)];
self.retweetButton.circleColor = [UIColor colorWithRed:0.04 green:0.83 blue:0.04 alpha:1.0];
self.retweetButton.lineColor = [UIColor colorWithRed:0.08 green:0.93 blue:0.08 alpha:1.0];
self.retweetButton.imageColorOn = [UIColor colorWithRed:0.26 green:0.96 blue:0.26 alpha:1.0];
[self.contentView addSubview:self.retweetButton];
// Reply Button
self.replyButton = [[DOFavoriteButton alloc] initWithFrame:CGRectZero];
[self.replyButton setBackgroundImage:[UIImage imageNamed:#"reply.png"] forState:UIControlStateNormal];
[self.contentView addSubview:self.replyButton];
//
// CONSTRAIN
//
// Name Label
[self.nameLabel autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:60];
[self.nameLabel autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:35];
[self.nameLabel autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:12];
[self.nameLabel autoAlignAxis:ALAxisVertical toSameAxisOfView:self.contentView];
// Username Label
[self.usernameLabel autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.nameLabel withOffset:0.0];
[self.usernameLabel autoSetDimension:ALDimensionHeight toSize:16.5];
[self.usernameLabel autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:58.0];
// Profile Picture
[self.profilePicture autoPinEdge:ALEdgeRight toEdge:ALEdgeLeft ofView:self.nameLabel withOffset:-10.0];
[self.profilePicture autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:12];
[self.profilePicture autoSetDimension:ALDimensionHeight toSize:35];
[self.profilePicture autoSetDimension:ALDimensionWidth toSize:35];
// Tweet Label
[self.tweetLabel autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.usernameLabel withOffset:8.0];
[self.tweetLabel autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:5.0];
Here is how I initiate the cell in my UITableViewController:
TwitterCell *cell = [self.tableView dequeueReusableCellWithIdentifier:#"TwitterCell"];
// Add Tap Listeners
UITapGestureRecognizer *nameLabelTap =
[[UITapGestureRecognizer alloc] initWithTarget:self
action:#selector(handleCellNameTap:)];
[cell.nameLabel addGestureRecognizer:nameLabelTap];
UITapGestureRecognizer *profileImageTap =
[[UITapGestureRecognizer alloc] initWithTarget:self
action:#selector(handleCellProfileImageTap:)];
[cell.profilePicture addGestureRecognizer:profileImageTap];
if (cell == nil) {
cell = [[TwitterCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"TwitterCell"];
}
NSDictionary *data = tweets[indexPath.row];
// NSDate
NSString *nameString = data[#"user"][#"name"];
NSString *screenName = data[#"user"][#"screen_name"];
NSString *tweetString = data[#"text"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
[dateFormatter setLocale:usLocale];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[dateFormatter setDateFormat: #"EEE MMM dd HH:mm:ss Z yyyy"];
NSDate *date = [dateFormatter dateFromString:[data objectForKey:#"created_at"]];
NSDate *currentDateNTime = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"GMT"]];
NSDateComponents *twitcomponents = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:date];
NSInteger twithour = [twitcomponents hour];
NSInteger twitminute = [twitcomponents minute];
NSInteger twitsecond = [twitcomponents second];
NSDateComponents *realcomponents = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:currentDateNTime];
NSInteger realhour = [realcomponents hour];
NSInteger realminute = [realcomponents minute];
NSInteger realsecond = [realcomponents second];
NSInteger hour = realhour - twithour;
NSInteger minute = realminute - twitminute;
NSInteger second = realsecond - twitsecond;
NSLog(#"Formatted hour: %ld, Formatted minute: %ld, Formatted second: %ld",(long)hour, (long)minute, (long)second);
int adjustedSeconds = ((int)minute * 60) - abs((int)second);
int adjustedMinutes = adjustedSeconds / 60;
if (hour==1 > minute > 0) {
int negmin = ((int)hour * 60) - abs((int)minute);
int posmin = abs(negmin);
NSString *strInt = [NSString stringWithFormat:#"%dm",posmin];
cell.timeAgo.text = strInt;
}else if (hour>0){
NSString *strInt = [NSString stringWithFormat:#"%ldh",(long)hour];
cell.timeAgo.text = strInt;
}else if (hour==1){
NSString *strInt = [NSString stringWithFormat:#"%ldh",(long)hour];
cell.timeAgo.text = strInt;
}else if(minute == 1 > second){
NSString *strInt = [NSString stringWithFormat:#"%lds",(long)second];
cell.timeAgo.text = strInt;
}else{
NSString *strFromInt = [NSString stringWithFormat:#"%dm",adjustedMinutes];
cell.timeAgo.text = strFromInt;
}
[cell.favoriteButton addTarget:self action:#selector(favoriteButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
[cell.retweetButton addTarget:self action:#selector(retweetButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
// Set Values
[cell.nameLabel setText:nameString];
cell.nameLabel.userInteractionEnabled = YES;
cell.profilePicture.userInteractionEnabled = YES;
cell.tweetLabel.text = tweetString;
cell.usernameLabel.text = [NSString stringWithFormat:#"#%#",screenName];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *imageUrl = [[data objectForKey:#"user"] objectForKey:#"profile_image_url"];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];
dispatch_async(dispatch_get_main_queue(), ^{
cell.profilePicture.image = [UIImage imageWithData:data];
CALayer *imageLayer = cell.profilePicture.layer;
[imageLayer setCornerRadius:18];
[imageLayer setMasksToBounds:YES];
});
});
Is the tableview's delegate and datasource all set? You can do that by setting:
self.tableView.delegate = self;
self.tableView.dataSource = self;
in your viewDidLoad method.
And are you running the numberOfSectionsInTableView: and the numberOfRowsInSection: methods also?
I assume you are initializing the cell in the cellForRowAtIndexPath:, and do you remember to return the cells in there?

Displaying a string with multiple attributes in a label

I need to display a string which will change every second.
For example :
View will refresh in 10 sec
View will refresh in 09 sec
View will refresh in 08 sec
View will refresh in 07 sec
..
View will refresh in 0 sec
The above string needs to be displayed with multiple properties of text, like-
1) The color of text - 'View will refresh in _ sec' will be White
2) The color of number - '10' , '09' ... will be Yellow.
As displayed in reference below :
How can I achieve this using only one label?
Many thanks in advance.
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] init];
[str appendAttributedString:[[NSAttributedString alloc] initWithString:#"Will change in " attributes:#{ NSFontAttributeName : [UIFont systemFontOfSize:17], NSForegroundColorAttributeName : [UIColor whiteColor] }]];
[str appendAttributedString:[[NSAttributedString alloc] initWithString:#"10 sec" attributes:#{ NSFontAttributeName : [UIFont systemFontOfSize:19], NSForegroundColorAttributeName : [UIColor yellowColor] }]];
myLabel.attributedText = str;
You can use string attributes like this (DOC):
NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:yourString];
[attr addAttribute: NSForegroundColorAttributeName value: [UIColor blackColor] range: NSMakeRange(0, 4)]; // color for char 0 to 4
[attr addAttribute: NSForegroundColorAttributeName value: [UIColor blueColor] range: NSMakeRange(4, 8)]; // color for char 4 to 8
[myLabel setAttributedText: attr];
Then to include variables in your NSString, you can use :
[NSString stringWithFormat:#"Hello %# !", myVariable]; // %# will be replace by myVariable
Try this
- (void)viewDidLoad
{
[super viewDidLoad];
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:#selector(updateLabelText:) userInfo:nil repeats:YES];
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] init];
[str appendAttributedString:[[NSAttributedString alloc] initWithString:#"Will change in " attributes:#{ NSFontAttributeName : [UIFont systemFontOfSize:17], NSForegroundColorAttributeName : [UIColor whiteColor] }]];
[str appendAttributedString:[[NSAttributedString alloc] initWithString:#"10 Sec" attributes:#{ NSFontAttributeName : [UIFont systemFontOfSize:19], NSForegroundColorAttributeName : [UIColor yellowColor] }]];
myLabel.attributedText = str;
}
- (NSString *)extractNumberFromText:(NSString *)text
{
NSCharacterSet *nonDigitCharacterSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
return [[text componentsSeparatedByCharactersInSet:nonDigitCharacterSet] componentsJoinedByString:#""];
}
-(void)updateLabelText:(NSTimer *) timerLocal
{
int labelCount = [[self extractNumberFromText:myLabel.text]intValue];
if (labelCount!=0)
{
labelCount--;
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] init];
[str appendAttributedString:[[NSAttributedString alloc] initWithString:#"Will change in " attributes:#{ NSFontAttributeName : [UIFont systemFontOfSize:17], NSForegroundColorAttributeName : [UIColor whiteColor] }]];
[str appendAttributedString:[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:#"%i Sec",labelCount] attributes:#{ NSFontAttributeName : [UIFont systemFontOfSize:19], NSForegroundColorAttributeName : [UIColor yellowColor] }]];
myLabel.attributedText = str;
}
else
{
[timerLocal invalidate];
}
}
create a label in storyboard set the constraint such that it can accommodate variable width
name the label as myLabel ;
here is .m file
//
// ViewController.m
// TimerLogic
//
//
#import "ViewController.h"
#interface ViewController ()
{
NSInteger currentTime ;
NSTimer *myTimer ;
}
#end
#implementation ViewController
#synthesize myLabel ;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
currentTime = 10 ;
[self.view addSubview:myLabel];
myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(createLabel:) userInfo:nil repeats:YES] ;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)createLabel:(NSTimer *)theTimer
{
if(currentTime == 10)
{
myLabel.backgroundColor = [UIColor redColor] ;
myLabel.text = #"Thats me" ;
myLabel.textColor = [UIColor yellowColor];
myLabel.translatesAutoresizingMaskIntoConstraints = NO ;
// NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:#"V: | -offsetTop-[label]" options:0 metrics:#{#"offsetTop":#100 } views:NSDictionaryOfVariableBindings(myLabel)];
}
if(currentTime == 9)
{
myLabel.backgroundColor = [UIColor greenColor] ;
myLabel.text = #"Thats me again 1" ;
myLabel.textColor = [UIColor whiteColor];
}
if (currentTime == 8)
{
myLabel.backgroundColor = [UIColor greenColor] ;
myLabel.text = #"Thats me again 2" ;
myLabel.textColor = [UIColor blackColor];
}
// like that for all values
if(currentTime == 7)
{
myLabel.backgroundColor = [UIColor purpleColor] ;
myLabel.text = #"Thats me again 3" ;
[myTimer invalidate ] ;
myLabel.textColor = [UIColor yellowColor];
}
currentTime-- ;
}
#end
If it is in webview than we can use CSS but it's UILabel so u can use below links for UILabels:-
1) https://github.com/AliSoftware/OHAttributedLabel/
2) https://github.com/mattt/TTTAttributedLabel/
3) https://github.com/joaoffcosta/UILabel-FormattedText
Hope this'll work for u.

MPMoviePlayerController won't play when using Storyboard / Shows black screen

I was trying to play a video in background in my app, but it didn't work when I was using Storyboard. I read something about ARC and tried everything, but my video won't simply play. I tried the exact same thing but with another project where I deleted the Storyboard-file, and there it worked. I need to use this in my project where I'm using Storyboard. Please help me.
Here's the code:
ViewController.m:
#import "AnimatedLoginViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import <QuartzCore/QuartzCore.h>
#interface ViewController (){
MPMoviePlayerController *player;
}
#property (nonatomic, strong) MPMoviePlayerController *player;
#end
#implementation ViewController
#synthesize player;
- (void)viewDidLoad
{
[super viewDidLoad];
CGRect screen = [[UIScreen mainScreen] bounds];
NSURL *movieUrl = [[NSBundle mainBundle] URLForResource:#"background" withExtension:#"mp4"];
self.player = [[MPMoviePlayerController alloc] initWithContentURL:movieUrl];
player.view.frame = screen;
player.scalingMode = MPMovieScalingModeFill;
[self.player setControlStyle:MPMovieControlStyleNone];
[self.view addSubview:player.view];
[player prepareToPlay];
UIImageView *logo = [[UIImageView alloc] initWithFrame:CGRectMake(65, 90, 190, 40)];
logo.backgroundColor = [UIColor clearColor];
[logo setImage:[UIImage imageNamed:#"logo_welcome.png"]];
[self.view addSubview:logo];
UIFont *boldFont = [UIFont fontWithName:#"HelveticaNeue-Bold" size:16.0];
UIFont *defaultFont = [UIFont fontWithName:#"HelveticaNeue" size:16.0];
NSDictionary * attributes = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[UIColor whiteColor], defaultFont, nil] forKeys:[NSArray arrayWithObjects:NSForegroundColorAttributeName, NSFontAttributeName, nil]];
NSDictionary * attributesBold = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[UIColor whiteColor], boldFont, nil] forKeys:[NSArray arrayWithObjects:NSForegroundColorAttributeName, NSFontAttributeName, nil]];
attributes = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[UIColor blackColor], defaultFont, nil] forKeys:[NSArray arrayWithObjects:NSForegroundColorAttributeName, NSFontAttributeName, nil]];
attributesBold = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[UIColor blackColor], boldFont, nil] forKeys:[NSArray arrayWithObjects:NSForegroundColorAttributeName, NSFontAttributeName, nil]];
UIButton *emailButton = [UIButton buttonWithType:UIButtonTypeCustom];
[emailButton setFrame:CGRectMake(10, screen.size.height==568?455:370, 300, 43)];
attributedString = [[NSMutableAttributedString alloc] init];
[attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:#"Enter your work " attributes:attributes]];
[attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:#"Email" attributes:attributesBold]];
[emailButton setAttributedTitle:attributedString forState:UIControlStateNormal];
[emailButton setBackgroundImage:[UIImage imageNamed:#"SignInMailButton.png"] forState:UIControlStateNormal];
[emailButton setBackgroundImage:[UIImage imageNamed:#"SignInMailButtonTap.png"] forState:UIControlStateHighlighted];
[emailButton setBackgroundImage:[UIImage imageNamed:#"SignInMailButtonTap.png"] forState:UIControlStateSelected];
[emailButton setEnabled:YES];
[self.view addSubview:emailButton];
boldFont = [UIFont fontWithName:#"HelveticaNeue-Bold" size:14.0];
defaultFont = [UIFont fontWithName:#"HelveticaNeue" size:14.0];
attributes = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[UIColor grayColor], defaultFont, nil] forKeys:[NSArray arrayWithObjects:NSForegroundColorAttributeName, NSFontAttributeName, nil]];
attributesBold = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[UIColor whiteColor], boldFont, nil] forKeys:[NSArray arrayWithObjects:NSForegroundColorAttributeName, NSFontAttributeName, nil]];
UIButton *signInButton = [UIButton buttonWithType:UIButtonTypeCustom];
[signInButton setFrame:CGRectMake(10, screen.size.height==568?500:410, 300, 43)];
attributedString = [[NSMutableAttributedString alloc] init];
[attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:#"Do you have an activation code? " attributes:attributes]];
[attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:#"Enter now" attributes:attributesBold]];
[signInButton setAttributedTitle:attributedString forState:UIControlStateNormal];
[signInButton setEnabled:YES];
[self.view addSubview:signInButton];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(playVideo)
name:MPMoviePlayerReadyForDisplayDidChangeNotification
object:player];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayerDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:self.player];
[player play];
}
- (void)moviePlayerDidFinish:(NSNotification *)note
{
if (note.object == self.player) {
NSInteger reason = [[note.userInfo objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey] integerValue];
if (reason == MPMovieFinishReasonPlaybackEnded)
{
[self.player play];
}
}
}
-(void)playVideo{
[player play];
}
#end

Terminated due to Memory Error when load number of view into UIScrollView

I am using UIScrollView in my app that 25 view first time.
user scroll on bottom next 25 view add in scrollview.
I am still entirely not sure this is a memory problem.But i didn't found the code cause of the Memory Problem.
Even I have checked memory leak issue through the instrument tool there is no memory leak.
My code:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
float scrollViewHeight = _scrl_ipad.frame.size.height;
float scrollContentSizeHeight = _scrl_ipad.contentSize.height;
float scrollOffset = _scrl_ipad.contentOffset.y;
if (scrollOffset == 0)
{
}
else if (scrollOffset + scrollViewHeight == scrollContentSizeHeight)
{
if (scrl_bottom_reload_view)
{
scrl_bottom_reload_view=nil;
[scrl_bottom_reload_view release];
}
scrl_bottom_reload_view = [[UIView alloc]initWithFrame:CGRectMake(10, scrollContentSizeHeight-100, _scrl_ipad.frame.size.width-20, 60.0)];
scrl_bottom_reload_view.tag = -50;
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake((_scrl_ipad.frame.size.width/2)-100, 10, 200, 40)];
lbl.font = [UIFont fontWithName:#"ArialMT" size:22];
lbl.textColor = [UIColor darkGrayColor];
lbl.backgroundColor = [UIColor clearColor];
lbl.text = #"Loading deals...";
[scrl_bottom_reload_view addSubview:lbl];
[lbl release];
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
activityIndicator.alpha = 1.0;
activityIndicator.color = [UIColor lightGrayColor];
activityIndicator.frame = CGRectMake((_scrl_ipad.frame.size.width/2)-150, 12, 37, 37);
activityIndicator.hidesWhenStopped = NO;
[scrl_bottom_reload_view addSubview:activityIndicator];
[activityIndicator startAnimating];
scrl_bottom_reload_view.hidden = FALSE;
scrl_bottom_reload_view.backgroundColor = [UIColor clearColor];
[self.scrl_ipad addSubview:scrl_bottom_reload_view];
[self performSelector:#selector(LoadScrl) withObject:nil afterDelay:0.3];
}
}
-(void)LoadScrl
{
//called api and fill arrayalldeals arry
[self func_scrl_ipad];
}
-(void)func_scrl_ipad
{
NSArray *viewsToRemove = [_scrl_ipad subviews];
for (UIView *view in viewsToRemove)
{
[view removeFromSuperview];
view = nil;
}
int temp;
if([arrayalldeals count] % 2 == 0)
{
temp = ([arrayalldeals count] / 2);
}
else
{
temp = ([arrayalldeals count] / 2) + 1;
}
_scrl_ipad.contentSize = CGSizeMake(768,(258*temp)+150);
_scrl_ipad.showsVerticalScrollIndicator=NO;
int x = 35;
int y = 35;
for (int i = 1 ; i <= [arrayalldeals count]; i++)
{
UIView *bgview = [[UIView alloc]initWithFrame:CGRectMake(x, y, 328, 243)];
bgview.backgroundColor = [UIColor whiteColor];
//bgview.layer.borderWidth = 0;
//bgview.layer.cornerRadius = 0;
bgview.tag = i;
//bgview.layer.masksToBounds = YES;
//bgview.layer.borderColor =[[UIColor clearColor] CGColor];
//bgview.layer.shadowColor = [[UIColor whiteColor] CGColor];
//bgview.layer.shadowOffset = CGSizeMake(0.0, 0.0);
//bgview.layer.shadowOpacity = 0.0;
AsyncImageView *imageView = [[AsyncImageView alloc] initWithFrame:CGRectMake(0, 0, 328, 223)];
imageView.contentMode = UIViewContentModeScaleAspectFill;
imageView.clipsToBounds = YES;
imageView.layer.cornerRadius = 0;
imageView.imageURL =[NSURL URLWithString:[NSString stringWithFormat:#"%#uploads/%#-5.jpg",app.Main_url,[[arrayalldeals objectAtIndex:i-1] objectForKey:#"deal_id"]]];
//cell.autoresizesSubviews=YES;
[bgview addSubview:imageView];
[imageView release];
UIView *shadoeview = [[UIView alloc]initWithFrame:CGRectMake(0,115, 328, 112)];
CAGradientLayer *bgLayer = [BackgroundLayer greyGradient];
bgLayer.frame = shadoeview.bounds;
[shadoeview.layer insertSublayer:bgLayer atIndex:0];
shadoeview.alpha = 0.9;
[bgview addSubview:shadoeview];
[shadoeview release];
UIImageView *img_discount = [[UIImageView alloc]initWithFrame:CGRectMake(0,0, 57, 57)];
img_discount.image = [UIImage imageNamed:#"discount_tag.png"];
[bgview addSubview:img_discount];
[img_discount release];
UILabel *lbl_disc_text=[[UILabel alloc]init];
lbl_disc_text.frame=CGRectMake(-2,-10,100,20);
lbl_disc_text.backgroundColor=[UIColor clearColor];
lbl_disc_text.font = [UIFont fontWithName:#"ArialMT" size:14];
lbl_disc_text.textColor = [UIColor whiteColor];
int disc = 0;
if([NSNull null] != [[arrayalldeals objectAtIndex:i-1] objectForKey:#"value"])
{
int main_price = [[[arrayalldeals objectAtIndex:i-1] objectForKey:#"value"] intValue];
int disc_price = [[[arrayalldeals objectAtIndex:i-1] objectForKey:#"price"] intValue];
int multiply = disc_price *100 /main_price;
disc = 100 - multiply;
}
lbl_disc_text.text = [NSString stringWithFormat:#"- %d%%",disc];
[bgview addSubview:lbl_disc_text];
float degrees = -40; //the value in degrees
lbl_disc_text.transform = CGAffineTransformMakeRotation(degrees * M_PI/180);
[lbl_disc_text release];
UILabel *lbl_desc=[[UILabel alloc]init];
lbl_desc.frame=CGRectMake(8,162, 240, 50);
lbl_desc.backgroundColor=[UIColor clearColor];
lbl_desc.font = [UIFont fontWithName:#"Arial Rounded MT Bold" size:16];
lbl_desc.textColor = [UIColor whiteColor];
lbl_desc.numberOfLines = 2 ;
if([NSNull null] != [[arrayalldeals objectAtIndex:i-1] objectForKey:#"name"])
{
lbl_desc.text=[NSString stringWithFormat:#"%#",[[arrayalldeals objectAtIndex:i-1] objectForKey:#"name"]];
}
else
{
lbl_desc.text=#"";
}
[bgview addSubview:lbl_desc];
[lbl_desc release];
UILabel *lbl_unprice=[[UILabel alloc]init];
lbl_unprice.frame=CGRectMake(255,165,60,20);
lbl_unprice.backgroundColor=[UIColor clearColor];
lbl_unprice.textAlignment = NSTextAlignmentRight;
lbl_unprice.textColor = [UIColor whiteColor];
lbl_unprice.font = [UIFont fontWithName:#"ArialMT" size:14];
if([NSNull null] != [[arrayalldeals objectAtIndex:i-1] objectForKey:#"value"])
{
int unprice = [[[arrayalldeals objectAtIndex:i-1] objectForKey:#"value"] intValue];
lbl_unprice.text = [NSString stringWithFormat:#"$%d",unprice];
}
else
{
lbl_unprice.text=[NSString stringWithFormat:#"$0"];
}
[bgview addSubview:lbl_unprice];
[lbl_unprice release];
NSString *str_price_line;
if([NSNull null] != [[arrayalldeals objectAtIndex:i-1] objectForKey:#"value"])
{
int unprice = [[[arrayalldeals objectAtIndex:i-1] objectForKey:#"value"] intValue];
str_price_line = [NSString stringWithFormat:#"$%d",unprice];
}
else
{
str_price_line=[NSString stringWithFormat:#"$0"];
}
UIFont *font = [UIFont fontWithName:#"ArialMT" size:14];
CGSize size = [(str_price_line ? str_price_line : #"") sizeWithFont:font constrainedToSize:CGSizeMake(281, 9999) lineBreakMode:NSLineBreakByWordWrapping];
int temp = 60 - size.width;
UILabel *lbl_line=[[UILabel alloc]init];
lbl_line.frame=CGRectMake(253+temp,174,size.width+4,2);
lbl_line.backgroundColor=[UIColor colorWithRed:252.0/255.0 green:36.0/255.0 blue:148.0/255.0 alpha:1.0];
float degre = -20; //the value in degrees
lbl_line.transform = CGAffineTransformMakeRotation(degre * M_PI/250);
[bgview addSubview:lbl_line];
[lbl_line release];
UILabel *lbl_price=[[UILabel alloc]init];
lbl_price.frame=CGRectMake(215,180, 100, 35);
lbl_price.textAlignment = NSTextAlignmentRight;
lbl_price.backgroundColor=[UIColor clearColor];
lbl_price.font = [UIFont fontWithName:#"ArialMT" size:24];
lbl_price.textColor = [UIColor colorWithRed:93.0/255.0 green:202.0/255.0 blue:242.0/255.0 alpha:1.0];
if([NSNull null] != [[arrayalldeals objectAtIndex:i-1] objectForKey:#"price"])
{
int price = [[[arrayalldeals objectAtIndex:i-1] objectForKey:#"price"] intValue];
lbl_price.text = [NSString stringWithFormat:#"$%d",price];
}
else
{
lbl_price.text=[NSString stringWithFormat:#"$0"];
}
[bgview addSubview:lbl_price];
[lbl_price release];
UILabel *lbl_bottom_view=[[UILabel alloc]init];
lbl_bottom_view.frame=CGRectMake(0,223, 328,20);
lbl_bottom_view.backgroundColor=[UIColor darkGrayColor];
[bgview addSubview:lbl_bottom_view];
[lbl_bottom_view release];
UILabel *lbl_vertical1=[[UILabel alloc]init];
lbl_vertical1.frame=CGRectMake(100,223,2,20);
lbl_vertical1.backgroundColor=[UIColor grayColor];
[bgview addSubview:lbl_vertical1];
[lbl_vertical1 release];
UILabel *lbl_vertical2=[[UILabel alloc]init];
lbl_vertical2.frame=CGRectMake(222,223,2,20);
lbl_vertical2.backgroundColor=[UIColor grayColor];
[bgview addSubview:lbl_vertical2];
[lbl_vertical2 release];
UILabel *lbl_address=[[UILabel alloc]init];
lbl_address.frame=CGRectMake(4,226, 94, 14);
lbl_address.textAlignment = NSTextAlignmentCenter;
lbl_address.backgroundColor=[UIColor clearColor];
lbl_address.font = [UIFont fontWithName:#"ArialMT" size:12];
lbl_address.textColor = [UIColor whiteColor];
if ((NSNull *)app.city_dict == NULL)
{
lbl_address.text= #"Vancouver";
}
else
{
lbl_address.text=[NSString stringWithFormat:#"%#",[app.city_dict objectForKey:#"title"]];
}
[bgview addSubview:lbl_address];
[lbl_address release];
//LeftTime
NSString *strDatehere = [NSString stringWithFormat:#"%#",[[arrayalldeals objectAtIndex:i-1] objectForKey:#"d_expires"]];
NSDateFormatter *heredateFormatter = [[NSDateFormatter alloc] init];
[heredateFormatter setDateFormat:#"yyyy-MM-dd"]; // set date formate with your dates
NSDate *datehere = [heredateFormatter dateFromString: strDatehere];
NSTimeInterval timeDifference = [datehere timeIntervalSinceDate:[NSDate date]];
[heredateFormatter release];
double hours = timeDifference / 3600;
NSInteger remainder = ((NSInteger)timeDifference)% 3600;
double minutes = remainder / 60;
double seconds = remainder % 60;
NSString *strleft_time = [NSString stringWithFormat:#"%.0fh, %.0fm, %.0fs",hours,minutes,seconds];
UILabel *lbl_time=[[UILabel alloc]init];
lbl_time.frame=CGRectMake(105,226, 110, 14);
lbl_time.textAlignment = NSTextAlignmentCenter;
lbl_time.backgroundColor=[UIColor clearColor];
lbl_time.font = [UIFont fontWithName:#"ArialMT" size:12];
lbl_time.textColor = [UIColor whiteColor];
lbl_time.text=strleft_time;
[bgview addSubview:lbl_time];
[lbl_time release];
UILabel *lbl_bought=[[UILabel alloc]init];
lbl_bought.frame=CGRectMake(222,226, 98, 14);
lbl_bought.textAlignment = NSTextAlignmentCenter;
lbl_bought.backgroundColor=[UIColor clearColor];
lbl_bought.font = [UIFont fontWithName:#"ArialMT" size:12];
lbl_bought.textColor = [UIColor whiteColor];
lbl_bought.text= [NSString stringWithFormat:#"%# Bought",[[arrayalldeals objectAtIndex:i-1] objectForKey:#"buys"]];
[bgview addSubview:lbl_bought];
[lbl_bought release];
UIButton *btn_scrl=[UIButton buttonWithType:UIButtonTypeCustom];
[btn_scrl setFrame:CGRectMake(0,0, 328, 243)];
btn_scrl.tag=i-1;
[btn_scrl addTarget:self action:#selector(btn_scrl_tag:) forControlEvents:UIControlEventTouchUpInside];
[bgview addSubview:btn_scrl];
UIButton *btn_fav=[UIButton buttonWithType:UIButtonTypeCustom];
[btn_fav setFrame:CGRectMake(285,5, 35, 35)];
if([[[arrayalldeals objectAtIndex:i-1] objectForKey:#"user_faves"] isEqualToString:#"1"])
{
[btn_fav setBackgroundImage:[UIImage imageNamed:#"all_deals_fave_pink_icon.png"] forState:UIControlStateNormal];
}
else
{
[btn_fav setBackgroundImage:[UIImage imageNamed:#"all_deals_fave_icon.png"] forState:UIControlStateNormal];
}
[btn_fav.titleLabel setFont:[UIFont boldSystemFontOfSize:12]];
if([[[arrayalldeals objectAtIndex:i-1] objectForKey:#"faves"] isEqualToString:#"0"])
{
[btn_fav setTitle:#"" forState:UIControlStateNormal];
}
else
{
[btn_fav setTitle:[NSString stringWithFormat:#"%#",[[arrayalldeals objectAtIndex:i-1] objectForKey:#"faves"]] forState:UIControlStateNormal];
}
btn_fav.tag=i-1;
[btn_fav addTarget:self action:#selector(btn_favorite:) forControlEvents:UIControlEventTouchUpInside];
[bgview addSubview:btn_fav];
[_scrl_ipad addSubview:bgview];
[bgview release];
if(i % 2 == 0)
{
y = y + 258;
x = 35;
}
else
{
x = 399;
}
}
}
}
////
now api called more then 10 times i got Terminated due to Memory Pressure Error and App crase
Didn't understand, what are you trying to do? But found many bugs in your code. List out some of them.
1) In this line, you already set as nil and try to release nil object. This won't release any object, this is main reason for memory leak.
if (scrl_bottom_reload_view)
{
scrl_bottom_reload_view=nil;
[scrl_bottom_reload_view release];
}
2) Try to assign nil to local variable which does nothing.
for (UIView *view in viewsToRemove)
{
[view removeFromSuperview];
view = nil;
}
3) Where did you release this object.
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc].....
Suggestion : Above code is more complex, try with Tableview. Use xib to like this job. Otherwise more complex to design as well consume more time to develop.

Resources