Autoresize Custom UIAlertView - iphone

I made a custom UIAlertView, who look like this
http://www.odlgs.com/customAlertBefore.jpg
The problem is that when I rotate to another interface orientation the alert change it's size and looks like this:
http://www.odlgs.com/customAlertAfter.jpg
I made a NSNotification that allows me to resize controls when I switch to another interface orientation, but doesn't work with my UIAlertView, and the autoresizingMask property do not works too, anyone that have experience the same problem or has some idea? here is the code:
/*** THIS IS THE CLASS OF MY CUSTOM ALERTVIEW ***/
#import "AlertTableViewController.h"
#import "Theme.h"
#implementation AlertTableViewController
#synthesize textField, caller, context, data;
-(id)initWithCaller:(id)_caller data:(NSArray*)_data title:(NSString*)_title andContext:(id)_context{
NSMutableString *messageString = [NSMutableString stringWithString:#"\n"];
tableHeight = 0;
if([_data count] != 0){
for(int i = 0; i < [_data count]; i++){
//[messageString appendString:#"\n\n"];
//tableHeight += 53;
tableHeight = 150;
}
}else{
//messageString = #"\n\n\n\n\n\n\n\n\n\n";
tableHeight = 207;
}
if(self = [super initWithTitle:_title message:messageString delegate:self cancelButtonTitle:nil otherButtonTitles:nil]){
self.caller = _caller;
self.context = _context;
self.data = _data;
[self prepare];
}
return self;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
[self.caller didSelectRowAtIndex:-1 withContext:self.context];
}
-(void)show{
self.hidden = YES;
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:#selector(myTimer:) userInfo:nil repeats:NO];
[super show];
}
-(void)myTimer:(NSTimer*)_timer{
self.hidden = NO;
[myTableView flashScrollIndicators];
}
//HERE I ADD THE CONTROLS TO MY CUSTOM ALERTVIEW
-(void)prepare{
self.autoresizingMask = UIViewAutoresizingFlexibleHeight;
textField = [[UITextField alloc] initWithFrame:CGRectMake(11, 50, 261, 30)];
textField.backgroundColor = [UIColor whiteColor];
textField.delegate = self;
myTableView = [[UITableView alloc] initWithFrame:CGRectMake(11, 115, 261, tableHeight) style:UITableViewStylePlain];
myTableView.scrollEnabled = NO;
myTableView.delegate = self;
myTableView.dataSource = self;
UILabel *sourcesTitle = [[UILabel alloc] initWithFrame:CGRectMake(11, 90, 261, 20)];
sourcesTitle.text = #"Source";
sourcesTitle.textColor = [UIColor whiteColor];
sourcesTitle.backgroundColor = [UIColor clearColor];
sourcesTitle.font = [UIFont fontWithName:kLKTtFONT_NAME size:kLKTtFONT_LABEL_SIZE_17];
UIButton *ok = [UIButton buttonWithType:UIButtonTypeRoundedRect];
ok.frame = CGRectMake(11, 280, 120, 30);
[ok setTitle:#"Ok" forState:UIControlStateNormal];
[ok addTarget:self action:#selector(saveNetwork) forControlEvents:UIControlEventTouchDown];
UIButton *cancel = [UIButton buttonWithType:UIButtonTypeRoundedRect];
cancel.frame = CGRectMake(150, 280, 120, 30);
[cancel setTitle:#"Cancel" forState:UIControlStateNormal];
[cancel addTarget:self action:#selector(cancel) forControlEvents:UIControlEventTouchDown];
[self addSubview:sourcesTitle];
[self addSubview:ok];
[self addSubview:cancel];
[self addSubview:myTableView];
[self addSubview:textField];
[textField becomeFirstResponder];
UIImageView *imgView = [[[UIImageView alloc] initWithFrame:CGRectMake(11, 50, 261, 4)] autorelease];
imgView.image = [UIImage imageNamed:#"top.png"];
[self addSubview:imgView];
imgView = [[[UIImageView alloc] initWithFrame:CGRectMake(11, tableHeight+46, 261, 4)] autorelease];
imgView.image = [UIImage imageNamed:#"bottom.png"];
[self addSubview:imgView];
CGAffineTransform myTransform = CGAffineTransformMakeTranslation(0.0, 10);
[self setTransform:myTransform];
}
-(void)saveNetwork{
CreateNetworkCommunication *communication = [[CreateNetworkCommunication alloc] init];
communication.sourceId = [[[data objectAtIndex:selectedSource] valueForKey:#"Id"] integerValue];
communication.name = textField.text;
communication.delegate = self;
[communication doRequest];
}
-(void)finishSaveNetworkRequestWithResponse:(OwnerResult*)response{
if (response.StatusCode == 0) {
[super dismissWithClickedButtonIndex:0 animated:YES];
[self.caller refreshNetworks];
}
else {
UIAlertView *error = [[UIAlertView alloc] initWithTitle:self.title message:NSLocalizedString(#"alert.error-saving", nil) delegate:nil cancelButtonTitle:NSLocalizedString(#"OK", nil) otherButtonTitles: nil];
[error show];
[error release];
}
}
-(void)cancel{
[super dismissWithClickedButtonIndex:1 animated:YES];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = (UITableViewCell*) [tableView dequeueReusableCellWithIdentifier:#"ABC"];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:#"ABC"] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.font = [UIFont boldSystemFontOfSize:14];
}
if (selectedSource != indexPath.row)
cell.accessoryType = UITableViewCellAccessoryNone;
cell.textLabel.text = [[data objectAtIndex:indexPath.row] valueForKey:#"Name"];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//[self dismissWithClickedButtonIndex:0 animated:YES];
//[self.caller didSelectRowAtIndex:indexPath.row withContext:self.context];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
selectedSource = indexPath.row;
[tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
selectedSource = indexPath.row;
cell.accessoryType = UITableViewCellAccessoryNone;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [data count];
}
-(void)dealloc{
self.data = nil;
self.caller = nil;
self.context = nil;
[myTableView release];
[super dealloc];
}
/*** THIS IS THE VIEWCONTROLLER WHERE I IMPLEMENT THE CUSTOM ALERTVIEW ***/
#import "NetworkSelectorViewController.h"
#interface NetworkSelectorViewController ()
#end
#implementation NetworkSelectorViewController
#synthesize delegate, alert;
-(void)add {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(resizeTaxonomyView:) name:#"resizeTaxonomyView" object:nil];
alert = [[AlertTableViewController alloc] initWithCaller:self data:sources title:#"New Network" andContext:nil];
//UIAlertView * alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:#"%# %#", NSLocalizedString(#"button.new", nil), self.title] message:#"" delegate:self cancelButtonTitle:NSLocalizedString(#"button.cancel", nil) otherButtonTitles:NSLocalizedString(#"button.save", nil), nil];
//alert.alertViewStyle = UIAlertViewStylePlainTextInput;
//UITextField * alertTextField = [alert textFieldAtIndex:0];
//UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(11, 110, 261, 200) style:UITableViewStylePlain];
//UIButton* okButton = [[UIButton alloc] initWithFrame:CGRectMake(11, 30, 50, 50)];
//[alert addSubview:okButton];
//okButton.frame = CGRectMake(okButton.frame.origin.x, 400, okButton.frame.size.width, okButton.frame.size.height);
//alertTextField.keyboardType = UIKeyboardTypeAlphabet;
//alertTextField.placeholder = self.title;
//[alert addSubview:tableView];
//alert.data = [[NSArray alloc] initWithObjects:#"1",#"2", nil];
alert.delegate = self;
NSLog(#"ALERT SUBVIEWS: %#", alert.subviews);
[alert show];
alert.frame = CGRectMake(alert.frame.origin.x, alert.frame.origin.y, alert.frame.size.width, 370);
NSLog(#"X:%f Y:%f W:%f H:%f", alert.frame.origin.x, alert.frame.origin.y, alert.frame.size.width, alert.frame.size.height);
UIButton* button1 = (UIButton*)[alert.subviews objectAtIndex:2];
button1.frame = CGRectMake(0,300, 50, button1.frame.size.height);
//[alert release];
}
- (void)resizeTaxonomyView:(NSNotification *)notification {
// El mÈtodo recibe un objeto de tipo NSNotification cuya propiedad object
// alberga el objeto pasado como parametro. En este caso hacemos un casting
// del objeto a NSString.
if(UIInterfaceOrientationIsLandscape(self.interfaceOrientation))
alert.frame = CGRectMake(alert.frame.origin.x, alert.frame.origin.y, alert.frame.size.width, 500);
else
alert.frame = CGRectMake(alert.frame.origin.x, alert.frame.origin.y, 500, 1000);
}
The NSnotification works, the method triggers, but the alertview doesnt autoresize
uialertviewcustom

Related

IOS: Clear Previous content in Modal viewcontroller

In my application, I have used one modal viewcontroller which contains one TableView with multiple textfields.
Say My main viewcontroller called SridharViewController and the modal viewcontroller called ResultsViewController
There is one button in SridharViewController , touching that button will open the modal(ResultsViewController)
[self presentModalViewController:resultsViewController animated:YES];
And in the results view controller , There are many text fields which are aligned in the TableView. and one 'OK' button . pressing 'OK' button will dismiss the modal
[self dismissModalViewControllerAnimated:YES];
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"cellForRowAtIndexPath called");
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
//UITextField *formTextField = [[UITextField alloc] initWithFrame:CGRectMake(30, 11, 270, 30)];
UITextField *formTextField =nil;
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
if(indexPath.row == 0){
formTextField = [[UITextField alloc] initWithFrame:CGRectMake(30, 12, 270, 30)];
}
else{
formTextField = [[UITextField alloc] initWithFrame:CGRectMake(30, 11, 270, 30)];
}
}else{
if(indexPath.row == 0){
formTextField = [[UITextField alloc] initWithFrame:CGRectMake(50, 12, 670, 30)];
}
else{
formTextField = [[UITextField alloc] initWithFrame:CGRectMake(50, 11, 670, 30)];
}
}
formTextField.placeholder = [self.formFields objectAtIndex:indexPath.row];
formTextField.tag = indexPath.row;
formTextField.text=#"";
formTextField.adjustsFontSizeToFitWidth = YES;
formTextField.textColor = [UIColor blackColor];
formTextField.borderStyle = UITextBorderStyleNone;
formTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
[formTextField setAutocapitalizationType:UITextAutocapitalizationTypeNone];
[formTextField setAutocorrectionType:UITextAutocorrectionTypeNo];
formTextField.backgroundColor = [UIColor clearColor];
formTextField.textAlignment = UITextAlignmentLeft;
formTextField.delegate = self;
[formTextField setEnabled: YES];
[formTextField setReturnKeyType:UIReturnKeyNext];
[self.textFields addObject:formTextField];
[cell addSubview:formTextField];
return cell;
}
When I calling the modal view second time , the modal shows the previous content. I want to clear that previous content.
I have tried both updates and reload functions. None of them calling the cellForRowAtIndexPath method.
[self.theTable reloadInputViews];
Please provide me the best way to do this.
In viewWillAppear do the following
arrayOfInputs = [NSArray array];
[self.tableview reloadData];
where arrayOfInputs is where you store your objects that would display on tableview. After making the data source empty and reload table view, all the contents will clear. Then you can reload the table view with required data.
When you want to reload tableview please use below line
[self.tableview reloadData]
Add this code in ViewDidLoad method this will clear all textfield text
for (UIView *view in [self.view subviews]) {
if ([view isKindOfClass:[UITextField class]]) {
UITextField *textField = (UITextField *)view;
textField.text = #"";
}
}
I solved my problem by this code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSLog(#" cellForRowAtIndexPath create new cell %d",indexPath.row);
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
NSLog(#" cellForRowAtIndexPath update cell %d",indexPath.row);
//UITextField *formTextField = [[UITextField alloc] initWithFrame:CGRectMake(30, 11, 270, 30)];
for(UITextField *lbl in [cell subviews])
{
NSLog(#" removing UITextField from cell %d",indexPath.row);
if(lbl.tag == (indexPath.row+2)){
[lbl removeFromSuperview];
}
}
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
if(indexPath.row == 0){
self.tableTextField = [[UITextField alloc] initWithFrame:CGRectMake(30, 12, 270, 30)];
}
else{
self.tableTextField = [[UITextField alloc] initWithFrame:CGRectMake(30, 11, 270, 30)];
}
}else{
if(indexPath.row == 0){
self.tableTextField = [[UITextField alloc] initWithFrame:CGRectMake(50, 12, 670, 30)];
}
else{
self.tableTextField = [[UITextField alloc] initWithFrame:CGRectMake(50, 11, 670, 30)];
}
}
self.tableTextField .placeholder = [self.formFields objectAtIndex:indexPath.row];
self.tableTextField .tag = indexPath.row+2;
self.tableTextField .adjustsFontSizeToFitWidth = YES;
self.tableTextField .textColor = [UIColor blackColor];
self.tableTextField .borderStyle = UITextBorderStyleNone;
self.tableTextField .keyboardType = UIKeyboardTypeNumbersAndPunctuation;
[self.tableTextField setAutocapitalizationType:UITextAutocapitalizationTypeNone];
[self.tableTextField setAutocorrectionType:UITextAutocorrectionTypeNo];
self.tableTextField .backgroundColor = [UIColor clearColor];
self.tableTextField .textAlignment = UITextAlignmentLeft;
self.tableTextField .delegate = self;
self.tableTextField .text=#"";
[self.tableTextField setEnabled: YES];
[self.tableTextField setReturnKeyType:UIReturnKeyNext];
[cell addSubview:self.tableTextField ];
return cell;
}

When releasing the objects in the custom cell class app crashes

I have a problem with my app crashing when my custom TableViewCell gets released. The code that i tried is given below .It Didn't go for the names of the variouble.
The Cell gets initialized like the following in cellForRowAtIndexPath.
static NSString *CellIdentifier1 = #"CellIdentifier";
static NSString *CellIdentifier2 = #"Cell";
if (indexPath.section == 0 && indexPath.row==0)
{
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
if (cell == nil)
{
cell = [[[CustomCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier1] autorelease];
cell.backgroundView = [ [[UIImageView alloc] initWithImage:[ [UIImage imageNamed:#"dfdfdf.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ]autorelease];
}
[cell.fgfbutton addTarget:self action:#selector(callAction:) forControlEvents:UIControlEventTouchUpInside];
cell.myImageView.image=[UIImage imageNamed:#"fdfdfdf.png"];
cell.fddfdbutton.tag=indexPath.section+1;
return cell;
}
else if (indexPath.section == 1 && indexPath.row==0)
{
Customcellwithimage *cell = (Customcellwithimage *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
if (cell == nil)
{
cell = [[[Customcellwithimage alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier2] autorelease];
cell.backgroundView = [ [[UIImageView alloc] initWithImage:[ [UIImage imageNamed:#"fetrtrtrt.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ]autorelease];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
[cell.dfdfbutton1 addTarget:self action:#selector(callAction:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
and in my custom cell class i am releasing the cell objects in the dealloc methode.and in my custom cell i am doing like this
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
nameLabel = [[UILabel alloc]init];
[nameLabel setFont:[UIFont fontWithName:#"Helvetica-Bold" size:16]];
nameLabel.textAlignment = UITextAlignmentLeft;
nameLabel.textColor = [UIColor blackColor];
nameLabel.numberOfLines = 0;
nameLabel.backgroundColor =[UIColor clearColor];
nameLabel.adjustsFontSizeToFitWidth = NO;
sfdfbutton = [UIButton buttonWithType:UIButtonTypeCustom];
[sdsdbutton setImage:[UIImage imageNamed:#"_it.png"] forState:UIControlStateNormal];
[sdbutton setImage:[UIImage imageNamed:#"ed.png"] forState:UIControlStateSelected];
sdsdbutton.selected=NO;
myImageView = [[UIImageView alloc] init];
bottomborder=[[UIImageView alloc] init];
UIImage *img1 = [UIImage imageNamed:#"_bg.png"];
[bottomborder setImage:img1];
[self.contentView addSubview:nameLabel];
[self.contentView addSubview:myImageView];
}
return self;
}
- (void)layoutSubviews {
[super layoutSubviews];
//CGRect contentRect = self.contentView.bounds;
//CGFloat boundsX = contentRect.origin.x;
CGRect frame;
//frame= CGRectMake(0 ,0, 300, 135);
//cellview.frame = frame;
frame= CGRectMake(60 ,8, 220, 20);
nameLabel.frame = frame;
myImageView.frame = CGRectMake(10,6,40,40);
NSLog(#"nameLabel frame: %#", NSStringFromCGRect(myImageView.frame));
nhghbutton.frame =CGRectMake(4,12 + frame.origin.y + frame.size.height, 82, 35);
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
}
- (void)dealloc {
[bottomborder release];
[myImageView release];
[label release];
[super dealloc];
}
You are probably overreleasing your UIButton: sfdfbutton if you do [sfdfbutton release] in dealloc of your table view cell. That's because it is autoreleased object.
If this is not the problem, try running application with Instruments.
To solve these kinds of issues, start your app with NSZombieEnabled set to YES (Product > Edit Scheme... and add this to Environment Variables).
This will point out exactly which variable gets overreleased. You can also perform a static analysis of your program by typing Cmd+Shift+B.

Why doesn't my search table view appear when beginning search?

I've wired a UISearchDisplayController into my app along with a search bar. I've initialized it as so:
self.filteredObjectArray = [NSMutableArray arrayWithCapacity:[self.objectArray count]];
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 43)];
searchBar.delegate = self;
[self.view addSubview:searchBar];
UISearchDisplayController *searchDisplay = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
searchDisplay.delegate = self;
searchDisplay.searchResultsTableView.delegate = self;
searchDisplay.searchResultsDataSource = self;
searchDisplay.searchResultsDelegate = self;
Which is pretty much the way I've seen it in other examples. I've also implemented the appropriate delegate methods, with the important filterContentForSearchText and the shouldReload* methods shown below:
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
[self.filteredObjectArray removeAllObjects]; // First clear the filtered array.
for (XRay *xray in objectArray) {
NSString *combinedLabel = [self combinedLabel:xray];
if ([combinedLabel rangeOfString:searchText options:(NSCaseInsensitiveSearch)].location != NSNotFound) {
[self.filteredObjectArray addObject:xray];
}
}
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString scope:
[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
return YES;
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption
{
[self filterContentForSearchText:self.searchDisplayController.searchBar.text scope:
[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];
return YES;
}
However my search is not working when I give the search text box focus or input any characters. You'll also notice that the greyed out view does not appear over my regular table view.
EDIT
cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"XraySearchChoice";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
XRay *xray = nil;
if (tableView == self.searchDisplayController.searchResultsTableView) {
xray = [self.filteredObjectArray objectAtIndex:indexPath.row];
} else {
xray = [self.objectArray objectAtIndex:indexPath.row];
}
cell.textLabel.text = [self combinedLabel:xray];
return cell;
}
I figured out what was wrong and I'm a bit surprised to be honest. Once I set a property on the SearchTableViewController:
#property (nonatomic, strong) UISearchDisplayController *searchDisplay;
And updated my code to use that one, everything worked from there. Here is my initializing code with the new property.
- (void)viewDidLoad
{
self.filteredObjectArray = [NSMutableArray arrayWithCapacity:[self.objectArray count]];
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 43)];
searchBar.delegate = self;
self.tableView.tableHeaderView = searchBar;
self.searchDisplay = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
self.searchDisplay.delegate = self;
self.searchDisplay.searchResultsDataSource = self;
self.searchDisplay.searchResultsDelegate = self;
}
Try with below code it will help you
self.filteredObjectArray = [NSMutableArray arrayWithCapacity:[self.objectArray count]];
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 43)];
searchBar.delegate = self;
//[self.view addSubview:searchBar];
self.theTableView.tableHeaderView = searchBar;//theTableView your tableview object
UISearchDisplayController *searchDisplay = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
self.searchController = searchDisplay;
[searchBar release];
searchDisplay.delegate = self;
searchDisplay.searchResultsDataSource = self;
searchDisplay.searchResultsDelegate = self;

Custom uitableview cell issue

I have a custom UITableViewCell as such:
#implementation CellWithThreeSubtitles
#synthesize title, subTitle1, subTitle2, subTitle3;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
self.textLabel.backgroundColor = self.backgroundColor;
self.textLabel.opaque = NO;
self.textLabel.textColor = [UIColor blackColor];
self.textLabel.highlightedTextColor = [UIColor whiteColor];
self.textLabel.font = [UIFont boldSystemFontOfSize:22.0];
}
return self;
}
- (void)layoutSubviews
{
[super layoutSubviews];
CGRect contentRect = self.contentView.bounds;
CGRect frame = CGRectMake(35.0, 0, contentRect.size.width, 50.0);
self.textLabel.frame = frame;
UILabel *subLabel1 = [[UILabel alloc] init];
frame = CGRectMake(35.0, 34.0, contentRect.size.width, 25.0);
subLabel1.font = [UIFont systemFontOfSize:18.0];
subLabel1.backgroundColor = [UIColor clearColor];
subLabel1.text = subTitle1;
subLabel1.opaque = NO;
subLabel1.frame = frame;
[self.contentView addSubview:subLabel1];
UILabel *subLabel2 = [[UILabel alloc] init];
frame = CGRectMake(35.0, 54.0, contentRect.size.width, 25.0);
subLabel2.font = [UIFont boldSystemFontOfSize:18.0];
subLabel2.backgroundColor = [UIColor clearColor];
subLabel2.text = subTitle2;
subLabel2.opaque = NO;
subLabel2.frame = frame;
[self.contentView addSubview:subLabel2];
UILabel *subLabel3 = [[UILabel alloc] init];
frame = CGRectMake(contentRect.size.width-100.0, 54.0, contentRect.size.width, 25.0);
subLabel3.font = [UIFont systemFontOfSize:18.0];
subLabel3.backgroundColor = [UIColor clearColor];
subLabel3.text = subTitle3;
subLabel3.opaque = NO;
subLabel3.frame = frame;
[self.contentView addSubview:subLabel3];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)dealloc {
[super dealloc];
[subTitle4 release];
[subTitle3 release];
[subTitle2 release];
[subTitle1 release];
[title release];
}
When I implement it in my UITableView like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
int section = [indexPath indexAtPosition:0];
static NSString *kCustomCellID = #"AppointmentCellID";
CellWithThreeSubtitles *cell = (CellWithThreeSubtitles *)[tableView dequeueReusableCellWithIdentifier:kCustomCellID];
if (cell == nil) {
cell = (CellWithThreeSubtitles *)[[[CellWithThreeSubtitles alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCustomCellID] autorelease];
}
switch (section) {
case 0:
if ([wineArray count]==0) {
cell.textLabel.text = #"No wine favorites selected yet";
}else{
cell.subTitle1 = [[wineArray objectAtIndex:indexPath.row] objectForKey:#"Varietal"];
cell.subTitle2 = [NSString stringWithFormat:#"Bin No. %#", [[wineArray objectAtIndex:indexPath.row] objectForKey:#"Bin"]];
cell.subTitle3 = [NSString stringWithFormat:#"$%#", [[wineArray objectAtIndex:indexPath.row] objectForKey:#"Price"]];
cell.textLabel.text = [NSString stringWithFormat:#"%# (%#)", [[wineArray objectAtIndex:indexPath.row] objectForKey:#"Name"], [[wineArray objectAtIndex:indexPath.row] objectForKey:#"Availability"]];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.userInteractionEnabled = NO;
break;
case 1:
if ([dinnerArray count]==0)
cell.textLabel.text = #"No dinner favorites selected yet";
else
cell.textLabel.text = [NSString stringWithFormat:#"%#", [[dinnerArray objectAtIndex:indexPath.row] objectForKey:#"Name"]];
break;
}
return cell;
}
the contents of the cell duplicates on top of itself every time the orientation of the device changes. Is it redrawing the cell every time the device rotates? And if so, How can I keep it from doing so?
You should be creating the subviews and adding them to your cell's subviews array in your -initWithStyle:reuseIdentifier: method. You only need to create the subviews once. The -layoutSubviews method is invoked repeatedly by the framework whenever the device orientation changes, to allow you to resize and/or move the subviews (plus make any other minor adjustments) to compensate for differences between the orientations.
I suspect layoutSubViews is being called on rotation, and re-drawing new labels on top of your old ones. If you remove any labels from the table cell at the beginning of layoutSubViews that would probably fix that issue, or you could create them in the init and then just position them in layoutSubViews.

Memory leak at text field in iphone sdk

I am getting memory leak at text fiels please suggest me how to resolve it.
I written the code in init() as:
eventTextField = nil;
eventTextField = [[UITextField alloc]initWithFrame:CGRectMake(10, 15, 300, 50)];
eventTextField.placeholder = #"Event Name";
[eventTextField setFont:[UIFont boldSystemFontOfSize:14]];
eventTextField.returnKeyType = UIReturnKeyDone;
eventTextField.keyboardAppearance = UIKeyboardAppearanceDefault;//Showing leak at this line
eventTextField.keyboardType = UIKeyboardTypeDefault;
eventTextField.delegate=self;
and I released it in dealloc method.
and in cellForRowIndex I am adding it as subview.
- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MasterViewIdentifier"];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:#"MasterViewIdentifier"] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIView* elementView = [[UIView alloc] initWithFrame:CGRectMake(20,170,320,280)];
elementView.tag = 0;
elementView.backgroundColor=[UIColor clearColor];
[cell.contentView addSubview:elementView];
[elementView release];
}
UIView* elementView = [cell.contentView viewWithTag:0];
elementView.backgroundColor=[UIColor clearColor];
for(UIView* subView in elementView.subviews)
{
[subView removeFromSuperview];
}
if(indexPath.section == 0 && indexPath.row == 0)
{
CorkItAppDelegate* appDelegate = (CorkItAppDelegate*)[[UIApplication sharedApplication] delegate];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
wineNameTitleLabel.numberOfLines = 0;
[wineNameTitleLabel setFont:[UIFont boldSystemFontOfSize:14]];
if(appDelegate.isNewWine == YES)
{
wineNameTitleLabel.textColor = [UIColor blackColor] ;
wineNameTitleLabel.text = appDelegate.getNewWineName;
}
else
{
if([event.eventWineName length]>0)
{
wineNameTitleLabel.textColor = [UIColor blackColor] ;
wineNameTitleLabel.text = event.eventWineName;
}
else
{
wineNameTitleLabel.text = #"Wine Name";
}
}
[elementView addSubview:wineNameTitleLabel];
}
else if(indexPath.section == 1)
{
if(isRightButton == YES)
{
eventTextField.enabled = NO;
}
else
{
eventTextField.enabled = YES;
}
if([event.eventName length] > 0)
{
eventTextField.text = event.eventName;
}
else
{
eventTextField.text = #"";
}
[elementView addSubview:eventTextField];
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
Hope I get wucik response from your side.
Thanks in advance,
Monish.
If you still need the eventTextField. You should create a property and instance variable for it. So that, you can your class own the eventTextField and release it in the dealloc. Like this:
#interface A {
UITextField *eventTextField;
}
#property (nonatomic, retain) UITextField *eventTextField;
#end
#implementation A
#synthesize eventTextField;
- (id)init {
eventTextField = [[UITextField alloc]init];
}
- (void)dealloc {
[eventTextField release];
}
#end
you should release the UITextField after adding it to the subview
[foo addSubview:eventTextField];
[eventTextField release];
eventTextField = nil; is unnecessary btw as eventTextField is a ivar is already zeroed (pointer set to 0x0(nil))