UITableViewCell initWithFrame:CGRectMake Autoresizing Problems..

Hello...
There are problems defining the Frame for my TableViewCell.. the documentation describes to approaches as mentioned (i've quoted them at the bottom), and I am implementing the first one - therfore, just adding views as subviews. It is looking like this - and is working more or less:
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
UILabel * nickLabel = [[[UILabel alloc] initWithFrame:CGRectMake(10.0, 12.0, 50.0, 20.0)] autorelease];
nickLabel.text = [tempDict valueForKey:@"id"];
nickLabel.font = [UIFont systemFontOfSize:12.0];
nickLabel.textAlignment = UITextAlignmentRight;
nickLabel.textColor = [UIColor blueColor];
nickLabel.autoresizingMask = UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:nickLabel];
the problem is, that as I am adding more and more subviews, I need more space for doing so. But it seems that my cellView is not "autoresizing" even if i define it with a special Rect like
cell = [[[UITableViewCell alloc] initWithFrame:CGRect(0.0, 0.0, 400.0, 100.0) reuseIdentifier:MyIdentifier] autorelease];
sure, this approach is not documented (the doc says use RectZero..) but i am just trying.. for example this Rect setting of my label looks like as if it would be in the third tableView Row.
UILabel * nickLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0.0, 100.0, 50.0, 20.0)] autorelease];
any ideas?
+■You should add subviews to a cell’s content view when your content layout can be specified+
+entirely with the appropriate autoresizing settings and when you don’t need to modify the default+
+behavior of the cell.+
+■ You should create a custom subclass when your content requires custom layout code or when+
+you need to change the default behavior of the cell, such as in response to editing mode.+

http://iphone.zcentric.com/2008/08/05/custom-uitableviewcell/ helped.
+change. How do I increase the size of each cell?+
+# mikezupan Says:+
+August 25th, 2008 at 8:39 am+
@Turbolag
+the only way I have found to edit the height of a cell is doing it in the tableView.+
+-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {+
+return 100.0; //returns floating point which will be used for a cell row height at specified row index+

Similar Messages

  • How to manage the uitableviewcell after being scrolled?

    Hi all.
    I manipulated the cell of the table view to be a custom one, which will be expanded(from height=50 to height=100) on selection and will be srinked to original(from height=100 to height=50) on second click or deselction. Now my problem is that i am selecting a row and without deselecting it or without clicking it for second time if i am scrolling the table ,the cell should reload to the original(height=50) srinked one. Here the view is reloading but the height for that row is not srinking(still height for that row remains to be 100). Can anyone have tried like this? Plz help me to sort out the problem.
    Tanks in advance.
    Satya.

    Well sorry for late responsse, here is the code:_
    @interface HomeControl : UIViewController<UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource >
              IBOutlet UITableView *newsTable;
              NSArray *dataArray;
              NSMutableArray *selectedRowArray,*clickedCountArray;
              CGRect frame;
    @property (nonatomic,retain) UITableView *newsTable;
    @property (nonatomic,retain) NSArray *dataArray;
    @property (nonatomic,retain) NSMutableArray *selectedRowArray,*clickedCountArray;
    @end
    @implementation HomeControl
    @synthesize newsTable,dataArray,selectedRowArray,clickedCountArray;
    - (void)viewDidLoad
              //table view section
                        NSDictionary *row1=[[NSDictionary alloc] initWithObjectsAndKeys:@"News",@"newsCatagory",@"News Title",@"newsTitle",nil],*row2=[[NSDictionary alloc] initWithObjectsAndKeys:@"News'it",@"newsCatagory",@"News Title",@"newsTitle",nil],*row3=[[NSDictionary alloc] initWithObjectsAndKeys:@"News",@"newsCatagory",@"News Title",@"newsTitle",nil],*row4=[[NSDictionary alloc] initWithObjectsAndKeys:@"Fashion",@"newsCatagory",@"Good Deal Title",@"newsTitle",nil],*row5=[[NSDictionary alloc] initWithObjectsAndKeys:@"News",@"newsCatagory",@"News Title",@"newsTitle",nil];
                        NSArray *a=[[NSArray alloc] initWithObjects:row1,row2,row3,row4,row5,nil];
                        self.dataArray=a;
                        [row1 release];[row2 release];[row3 release];[row4 release];[row5 release];[a release];
                        selectedRowArray=[[NSMutableArray alloc] initWithCapacity:dataArray.count];
                        clickedCountArray=[[NSMutableArray alloc] initWithCapacity:dataArray.count];
                        for(int i=0; i<[dataArray count]; i++)
                                  [selectedRowArray addObject:[NSNumber numberWithInt:0]];
                                  [clickedCountArray addObject:[NSNumber numberWithInt:0]];
    - (void)viewDidUnload
              // Release any retained subviews of the main view.
              // e.g. self.myOutlet = nil;
              self.newsTable=nil; self.selectedRowArray=nil;          self.clickedCountArray=nil;
              self.dataArray=nil;
              [super viewDidUnload];
    - (void)dealloc
              [newsTable release]; [selectedRowArray release]; [clickedCountArray release];
              [dataArray release];
        [super dealloc];
    #pragma mark Custom Methods
    -(void)cellWithDataInTableForCell:(TableDataCellControl*)tCell withIndexPath:(NSIndexPath*)ip
              NSUInteger r=[ip row];
              NSDictionary *rowdata=[self.dataArray objectAtIndex:r];
              tCell.newsL.text=[rowdata objectForKey:@"newsCatagory"];
              tCell.title.text=[rowdata objectForKey:@"newsTitle"];
              if(tCell.newsL.text==@"Fashion")
                        tCell.rowImage.image=[UIImage imageNamed:@"orange.png"];
              else if(tCell.newsL.text==@"News'it")
                        tCell.rowImage.image=[UIImage imageNamed:@"IT-Icon.png"];
                        tCell.rowImage.backgroundColor=[UIColor clearColor];
              else
                        tCell.rowImage.image=nil;
              NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
              [formatter setDateFormat:@"dd-MM-yyyy HH:mm"];
              tCell.timeL.text=[formatter stringFromDate:[NSDate date]];
              [formatter release];
    -(void)accessViewForCell:(TableDataCellControl*)tCell
              UILabel *l=[[UILabel alloc] initWithFrame:CGRectMake(0,0,10,12)];
              l.textAlignment=UITextAlignmentCenter;
              l.backgroundColor=[UIColor clearColor];
              l.textColor=[UIColor blueColor];
              if(tCell.selectedRow==0) l.text=@">";
              else l.text=@"<";
              tCell.accessoryView=l;
              tCell.accessoryView.userInteractionEnabled=YES;
              [l release];
    #pragma mark Table DataSource Methods
    -(NSInteger)tableView:(UITableView *)tv numberOfRowsInSection:(NSInteger)s
              return [self.dataArray count];
    -(NSString *)tableView:(UITableView *)tv titleForHeaderInSection:(NSInteger)s
              if(s==0)
                        return [NSString stringWithString:@"Actuallite"];
              else
                        return nil;
    -(UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)ip
              static NSString *cid=@"CID";
              TableDataCellControl *tCell=(TableDataCellControl *)[tv dequeueReusableCellWithIdentifier:cid];
              if([[clickedCountArray objectAtIndex:ip.row] intValue]%2==0)
                        if(tCell==nil)
                                  NSArray *cellNib=[[NSBundle mainBundle] loadNibNamed:@"TableCell" owner:self options:nil];
                                  for(id ob in cellNib)
                                            if([ob isKindOfClass:[TableDataCellControl class]])
                                                      tCell=(TableDataCellControl *)ob;
                        tCell.selectedRow=[[selectedRowArray objectAtIndex:ip.row] intValue];
                        tCell.rowClicked=[[clickedCountArray objectAtIndex:ip.row] intValue];
                        [self cellWithDataInTableForCell:tCell withIndexPath:ip];
                        [self accessViewForCell:tCell];
              else
                        if(tCell==nil)
                                  NSArray *cellNib=[[NSBundle mainBundle] loadNibNamed:@"TableCellExtended" owner:self options:nil];
                                  for(id ob in cellNib)
                                            if([ob isKindOfClass:[TableDataCellControl class]])
                                                      tCell=(TableDataCellControl *)ob;
                        tCell.selectedRow=[[selectedRowArray objectAtIndex:ip.row] intValue];
                        tCell.rowClicked=[[clickedCountArray objectAtIndex:ip.row] intValue];
                        [self cellWithDataInTableForCell:tCell withIndexPath:ip];
                        [self accessViewForCell:tCell];
              return tCell;
    -(void)tableView:(UITableView *)tv didSelectRowAtIndexPath:(NSIndexPath *)ip
              TableDataCellControl *tCell=(TableDataCellControl *)[tv cellForRowAtIndexPath:ip],*newCell;
              tCell.rowClicked+=1;
              [clickedCountArray replaceObjectAtIndex:ip.row withObject:[NSNumber numberWithInt:tCell.rowClicked]];
              if(tCell.selectedRow==0)
                        tCell.selectedRow=1;
                        [selectedRowArray replaceObjectAtIndex:ip.row withObject:[NSNumber numberWithInt:tCell.selectedRow]];
              else
                        tCell.selectedRow=0;
                        [selectedRowArray replaceObjectAtIndex:ip.row withObject:[NSNumber numberWithInt:tCell.selectedRow]];
              [tv reloadRowsAtIndexPaths:[NSArray arrayWithObject:ip] withRowAnimation:UITableViewRowAnimationFade];
              tCell=(TableDataCellControl*)[tv cellForRowAtIndexPath:ip];
              if(tCell!=nil)
                        for(id ob in tCell.contentView.subviews)
                                  [ob removeFromSuperview];
              NSArray *cellNib=[[NSBundle mainBundle] loadNibNamed:@"TableCellExtended" owner:self options:nil];
              for(id ob in cellNib)
                        if([ob isKindOfClass:[TableDataCellControl class]])
                                  newCell=(TableDataCellControl *)ob;
              [self cellWithDataInTableForCell:newCell withIndexPath:ip];
              //[self accessViewForCell:tCell];
              [tCell.contentView addSubview:newCell.contentView];
              if((tCell.selectedRow==0)&&(tCell.rowClicked%2==0))
                        [self tableView:tv didDeselectRowAtIndexPath:ip];
    -(void)tableView:(UITableView *)tv didDeselectRowAtIndexPath:(NSIndexPath *)ip
              [clickedCountArray replaceObjectAtIndex:ip.row withObject:[NSNumber numberWithInt:0]];
              [selectedRowArray replaceObjectAtIndex:ip.row withObject:[NSNumber numberWithInt:0]];
              int c,s;
              c=[[clickedCountArray objectAtIndex:ip.row] intValue];s=[[selectedRowArray objectAtIndex:ip.row] intValue];
              [tv reloadRowsAtIndexPaths:[NSArray arrayWithObject:ip] withRowAnimation:UITableViewRowAnimationFade];
              TableDataCellControl *tCell=(TableDataCellControl *)[tv cellForRowAtIndexPath:ip],*newCell;
              if(tCell!=nil)
                        for(id ob in tCell.contentView.subviews)
                                  [ob removeFromSuperview];
              NSArray *cellNib=[[NSBundle mainBundle] loadNibNamed:@"TableCell" owner:self options:nil];
              for(id ob in cellNib)
                        if([ob isKindOfClass:[TableDataCellControl class]])
                                  newCell=(TableDataCellControl *)ob;
              [self cellWithDataInTableForCell:newCell withIndexPath:ip];
              //[self accessViewForCell:tCell];
              [tCell.contentView addSubview:newCell.contentView];
    -(CGFloat)tableView:(UITableView *)tv heightForRowAtIndexPath:(NSIndexPath *)ip
              int cliked=[[clickedCountArray objectAtIndex:ip.row] intValue],selection=[[selectedRowArray objectAtIndex:ip.row] intValue];
              int check=(cliked%2==0)&&(selection==0)?0:1;
              switch (check)
                        case 0:
                                  return 49;
                                  break;
                        case 1:
                                  return 100;
                                  break;
                        default:
                                  return 49;
                                  break;
    @end

  • Define selected UIImageView inside UITableViewCell

    Hello all.
    I have my custom MyTableViewCell : UITableViewCell. Inside this cell I have three UIImageViews. I.e. redView, greenView and blueView.
    What I need to do is to handle what view has been touched and print this info into console.
    Please help me to solve this issue.
    Thank you in advance.

    Hello Ray!
    Thank you for your reply. I tried to implement #3 approach but got failed. The problem is that button touch event is not fired and I can't figure out why. Please see my code below.
    I have custom controller for my table
    @interface SummaryViewController : UIViewController <UIScrollViewDelegate, UITextViewDelegate,
    UITableViewDelegate, UITableViewDataSource> {
    UITableView *myTableView;
    @property (nonatomic, retain) UITableView *myTableView;
    -(void)btnClick;
    @end
    And I add button in cellForRowAtIndexPath event of this controller:
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = [indexPath row];
    UITableViewCell *cell = [myTableView dequeueReusableCellWithIdentifier:kNewsItemTableViewOffsetCell_ID];
    if (cell == nil) {
    cell = [[[NewsItemTableViewCell alloc] initWithFrame:CGRectZero
    reuseIdentifier:kNewsItemTableViewOffsetCell_ID] autorelease];
    // we are creating a new cell, setup its attributes
    if (row == 0) {
    //some business logic
    } else {
    UIButton *button = [[UIButton buttonWithType:UIButtonTypeCustom] initWithFrame:CGRectMake(85, 10, 44, 34)];
    [button setBackgroundImage:[UIImage imageNamed:@"defaultTab.png"] forState:UIControlStateNormal];
    [button setTitle:@"Okay" forState: UIControlStateHighlighted];
    [button setTitle:@"Okay" forState: UIControlStateNormal];
    [button addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    [((NewsItemTableViewCell *)cell).adContactsView addSubview:button];
    return cell;
    And finally I have button event handler in this controller:
    -(void)btnClick {
    NSLog(@"btnClick");
    My problem is that btnClick is not fired. But fired another delegate method didSelectRowAtIndexPath of UITableView.
    What am I doing wrong?
    Thanks.

  • How to edit label in custom UITableViewCell?

    Hi, I'm a newby in iPhone programming, I have created a custom UITableViewCell with 3 labels and I have populated an UITableView with some rows. I need to change the text of one of the labels when the user select the cell.
    I wrote this:
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *theCellSelected = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    theCellSelected = [theTableView cellForRowAtIndexPath:indexPath.row];
    UILabel *theLabelToEdit = (UILabel *)[theCellSelected viewWithTag:1];
    theLabelToEdit.text = @"Some Text..";
    ..but nothing happen to the label, the text doesn't change..
    What's wrong?
    Thank you!
    PS: sorry for my english, I'm italian and I don't speak it very well..

    Hi Zoodany, and welcome to the Dev Forum!
    zoodany wrote:
    I wrote this:
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    theTableView = tableView;
    // remove --> static NSString *CellIdentifier = @"Cell";
    UITableViewCell *theCellSelected;
    // remove --> = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    theCellSelected = [theTableView cellForRowAtIndexPath:indexPath]; // <-- remove '.row'
    UILabel *theLabelToEdit = (UILabel *)[theCellSelected viewWithTag:1];
    theLabelToEdit.text = @"Some Text..";
    Assuming your @interface, xib and DataSource methods are consistent with the above, the only thing stopping your code from working would be the 'indexPath.row' arg as commented. The lines which dequeue a cell won't prevent your code from running, though if any cells are actually in the queue, you'll have a memory leak there.
    However, I doubt the code you posted is the same as the code you tested. If you actually coded cellForRowAtIndexPath:indexPath.row, you should have gotten a warning since 'row' is an int instead of a pointer. And if you had ignored that warning the program would have crashed at that line. This kind of mixup often happens when the programmer keys code into the forum instead of pasting it directly from the source file. Please copy and paste when posting your code here (also see the alert about formatting code, the first topic of the forum), ok?
    If indeed 'indexPath.row' is a red herring, I think we need to look elsewhere in your project for the problem.
    I have created a custom UITableViewCell
    This contradicts your code somewhat. If you subclassed UITableViewCell, you'd normally add ivars with matching @properties to the custom cell so you could access the subviews as cell.label1, cell.label2, etc. Using viewWithTag to find one of the labels suggests that you simply added the labels to vanilla UITableViewCell objects rather that subclassing (adding the labels without subclassing is probably the best choice if no further customization is required).
    So please let us know whether or not you actually defined a subclass of UITableViewCell. Assuming you didn't, here's an example of how to add labels to your cells (only two labels are added below to simplify the example):
    // Customize the appearance of table view cells.
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
    reuseIdentifier:CellIdentifier] autorelease];
    // make label 1
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 3, 140, 38)];
    label.text = @"Label 1";
    label.backgroundColor = [UIColor lightGrayColor];
    label.font = [UIFont boldSystemFontOfSize:20];
    label.tag = 1;
    [cell.contentView addSubview:label];
    [label release];
    // make label 2
    label = [[UILabel alloc] initWithFrame:CGRectMake(160, 3, 140, 38)];
    label.text = @"Label 2";
    label.backgroundColor = [UIColor yellowColor];
    label.font = [UIFont boldSystemFontOfSize:20];
    label.tag = 2;
    [cell.contentView addSubview:label];
    [label release];
    // Set up the cell...
    return cell;
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *theCellSelected = [tableView cellForRowAtIndexPath:indexPath];
    UILabel *theLabelToEdit = (UILabel *)[theCellSelected viewWithTag:1];
    theLabelToEdit.text = @"Some Text..";
    Note that 'tableView' is used in the delegate method instead of an instance variable such as 'theTableView'. The 'tableView' parameter will always be set to the address of the table view which is calling the delegate method, so there's no need to use an ivar in this case. In fact, 'theTableView' could also be the cause of your problem. For example if you made the table view in IB, you might have forgotten to connect the 'theTableView' outlet of the controller (or File's Owner) to the UITableView object. So you might also check that connection, though the code above doesn't depend on it.
    Hope that helps!
    - Ray

  • Problem with a method to modify the transparency of a Label UILabel

    HI
    I Have create a small project which can modify the brightness ( or the transparency ) of a label
    UIlabel
    So the code
    File .m
    ControlBoxCookeAppDelegate.m
    Code :
    Code:
    *// ControlBoxCookeAppDelegate.m*
    *// Control Box Cooke*
    *// Created by Bruno on 1/11/10.*
    *// Copyright _MyCompanyName_ 2010. All rights reserved.*
    *#import "SerialManager.h"*
    *#import "ControlBoxCookeAppDelegate.h"*
    *#import "PickerViewController.h"*
    *#include <fcntl.h>*
    *#include "Led.h"*
    *@implementation ControlBoxCookeAppDelegate*
    *@synthesize window;*
    *- (void)applicationDidFinishLaunching:(UIApplication *)application {*
    *// Override point for customization after application launch*
    *[window makeKeyAndVisible];*
    //RootViewController.m
    *- (void)applicationDidFinishLaunching:(UIApplication *)application {*
    * pvController = [[PickerViewController alloc] initWithNibName:@"pickerview"/@"MainWindow"*//@"Control Box Cooke"//*@"PickerView"/ bundle:[NSBundle mainBundle]];*
    * Led_Operateur= [[Led alloc] initWithFrame:CGRectMake(20,50,280,20)];*
    * Led_Operateur.text=@" ";*
    * [Led_Operateur setBackgroundColor: [ UIColor colorWithWhite:1.0 alpha: 0.5]];*
    * [pvController.view addSubview:Led_Operateur];*
    * [window addSubview:pvController.view];*
    * // Override point for customization after application launch*
    * [window makeKeyAndVisible];*
    *- (void)dealloc {*
    * [Led_Operateur release];*
    * [pvController release];*
    *[window release];*
    *[super dealloc];*
    -(void)Modifie_luma:(CGFloat)luma
    * pvController = [[PickerViewController alloc] initWithNibName:@"pickerview" bundle:[NSBundle mainBundle]];*
    * Led_Operateur= [[UILabel alloc] initWithFrame:CGRectMake(20,50,280,20)];*
    * Led_Operateur.text=@" ";*
    * [Led_Operateur setBackgroundColor: [ UIColor colorWithWhite:1.0 alpha: luma]];*
    * [pvController.view addSubview:Led_Operateur];*
    * [window addSubview:pvController.view];*
    * [window makeKeyAndVisible];*
    @end
    file.h
    Code :
    Code:
    *// ControlBoxCookeAppDelegate.h*
    *// Control Box Cooke*
    *// Created by Bruno on 1/11/10.*
    *// Copyright _MyCompanyName_ 2010. All rights reserved.*
    *#import <UIKit/UIKit.h>*
    *#import "SerialManager.h"*
    *#import "led.h"*
    *@class PickerViewController;*
    *@interface ControlBoxCookeAppDelegate : NSObject <UIApplicationDelegate> {*
    *UIWindow window;
    * PickerViewController pvController;
    * SerialManager portCunima;
    * int portin,portout; // numero de port de com in-out*
    * UILabel Led_Operateur;
    -(void)Modifie_luma:(CGFloat)luma;
    *@property (nonatomic, retain) IBOutlet UIWindow window;
    @end
    To the initialization no problem my label UILabel display itself very well with the transparency
    of 50% ( alpha=0.5)
    But when I modify this transparency with a button, in my window iPhone
    the program call the method Modifie_Luma witch is the class
    ControlBoxCookeAppDelegate
    the program go on to this method, (I have fixe a breakpoint) but impossible to various this transparency.
    So if I change in method (void)applicationDidFinishLaunching
    the transparency
    example alpha =0,5 => alpha =0,8
    Code :
    Code:
    * [Led_Operateur setBackgroundColor: [ UIColor colorWithWhite:1.0 alpha: 0.8]];*
    this example go on
    resume
    when I change the transparency in the method
    (void)applicationDidFinishLaunching it 's OK
    when I change the transparency in the method
    -(void)Modifie_luma it's not OK
    Have you an explanation ?

    So the code , sorry but no marker for the code in post
    How do you do ?
    // ControlBoxCookeAppDelegate.h
    // Control Box Cooke
    // Created by Bruno on 1/11/10.
    // Copyright _MyCompanyName_ 2010. All rights reserved.
    #import <UIKit/UIKit.h>
    #import "SerialManager.h"
    #import "led.h"
    @class PickerViewController;
    @interface ControlBoxCookeAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
    PickerViewController *pvController;
    SerialManager *portCunima;
    int portin,portout; // numero de port de com in-out
    UILabel *Led_Operateur;
    -(void)Modifie_luma:(CGFloat)luma;
    @property (nonatomic, retain) IBOutlet UIWindow *window;
    @end
    // ControlBoxCookeAppDelegate.m
    // Control Box Cooke
    // Created by Bruno on 1/11/10.
    // Copyright _MyCompanyName_ 2010. All rights reserved.
    #import "SerialManager.h"
    #import "ControlBoxCookeAppDelegate.h"
    #import "PickerViewController.h"
    #include <fcntl.h>
    #include "Led.h"
    @implementation ControlBoxCookeAppDelegate
    @synthesize window;
    - (void)applicationDidFinishLaunching:(UIApplication *)application {
    // Override point for customization after application launch
    [window makeKeyAndVisible];
    //RootViewController.m
    - (void)applicationDidFinishLaunching:(UIApplication *)application {
    pvController = [[PickerViewController alloc] initWithNibName:@"pickerview"/@"MainWindow"*//@"Control Box Cooke"//*@"PickerView"/ bundle:[NSBundle mainBundle]];
    Led_Operateur= [[Led alloc] initWithFrame:CGRectMake(20,50,280,20)];
    Led_Operateur.text=@" ";
    [Led_Operateur setBackgroundColor: [ UIColor colorWithWhite:1.0 alpha: 0.5]];
    [pvController.view addSubview:Led_Operateur];
    [window addSubview:pvController.view];
    Led *ZoneA;
    CGRect Dimension;
    ZoneA = [[Led alloc]initWithFrame:Dimension];
    [pvController.view addSubview:ZoneA];
    [window addSubview:pvController.view];
    [ZoneA Modifie_luma:0.5];
    [ZoneA release];
    // Override point for customization after application launch
    [window makeKeyAndVisible];
    Led *Led1;
    CGRect frame;
    Led1=[[Led alloc] initWithFrame:frame];
    [pvController.view addSubview:Led1];
    [window addSubview:pvController.view];
    [Led1 release];
    [label release];
    [Error_message release];
    [path_port release];
    - (void)dealloc {
    [Led_Operateur release];
    [pvController release];
    [window release];
    [super dealloc];
    -(void)Modifie_luma:(CGFloat)luma
    pvController = [[PickerViewController alloc] initWithNibName:@"pickerview" bundle:[NSBundle mainBundle]];
    Led_Operateur= [[UILabel alloc] initWithFrame:CGRectMake(20,50,280,20)];
    Led_Operateur.text=@" ";
    [Led_Operateur setBackgroundColor: [ UIColor colorWithWhite:1.0 alpha: luma]];
    [pvController.view addSubview:Led_Operateur];
    [window addSubview:pvController.view];
    [window makeKeyAndVisible];
    @end

  • Scrolling problem with UIDatePicker

    Hi,
    I have implemented UIDatePicker from UICatalog sample but i could not scroll on PickerView. I have to touch on record one by one for scrolling and it doesn't give me smooth scroll. I have added this picker view on view only.
    Following is the my code,
    datePickerView = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 265, 320, 400)];
    datePickerView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    datePickerView.datePickerMode = UIDatePickerModeDate;
    datePickerView.userInteractionEnabled = YES;
    datePickerView.maximumDate = [NSDate date];
    [datePickerView addTarget:self action:@selector(datePickerValueChanged:) forControlEvents:UIControlEventValueChanged];
    datePickerView.hidden = YES;
    [self.view addSubview:datePickerView];
    Do you what is the problem.

    I'm reposting this from another thread I replied to:
    Just hold the mouse upside down and firmly press and scroll the ball for a few times. There's gunk in the sensors (dead skin cells, etc.) and it needs to be cleared — remember the old mice with the rubber ball? Well it the same except the ball is now on top! Next, I take a scrap of paper, fold it in half, and run it along between the ball and the hole to scoop up the loosened gunk. Short of taking the mouse apart to clean it, this is the easiest way to get the scroll ball working properly.
    Hope this works for you.

  • How to handle too many custom UITableViewCells in UITableView?

    In my iphone app, I need to display many custom rows (maybe thousands or even more) in the UITableView. I add one custom UIView onto each UITableViewCell in "- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath" function, so there will be allocate much memory for the all my custom UIViews. When I add 500 rows into the UITableView, the memory ran out, then the app crashed. I think maybe there is something wrong with my code or design, I don't know how to handle this (thousands custom rows in UITableView). Please help me.... Thanks very much..
    Below is the my code:(if I have thousands of rows, the following code will allocate thousands of CustomViews), is there any way that not allocate so many CustomViews?
    // Customize the appearance of table view cells.
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
    **cell = [[[UITableViewCell alloc] initWithFrame:CGRectMake(0, 0, 110, 25) reuseIdentifier:CellIdentifier] autorelease] ;
    // Set up the cell...
    CustomView *cellView = [[CustomView alloc]initWithFrame:CGRectMake(1, 1, 108, 24)];
    [cell addSubview: cellView];
    [cellView release];
    return cell;
    }

    Hi,
    well you should add the customView if you need to create a new cell only. Any reused cell will contain this customview allready since you've added it when the cell was created.
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithFrame:CGRectMake(0, 0, 110, 25) reuseIdentifier:CellIdentifier] autorelease];
    // Add customView to new cell's only
    CustomView *cellView = [CustomView alloc] initWithFrame:CGRectMake(1, 1, 108, 24)];
    [cell addSubview: cellView];
    [cellView release];
    // Set up the cell...
    return cell;

  • How can we find whether we clicked UIImage or text in UItableViewCell

    In tableview didselectrowatindexpath method how can we find if we click image in that cell[i mean the image which i set using cell.image ] or text in that cell[i mean the text which i set using cell.textlabel.text]
    Basically i have to do separate functionality if i click image or text....
    I have customized the cell and put view for this thing but bluecolor selection is not coming while i click that cell....
    Please help me out.....

    //////////// Custom tableviewcell....
    - (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier tableView:(UITableView*)tableview cellRow:(NSInteger)cellRow cellSection:(NSInteger)cellSection{
    if (self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) {
    // Initialization code
    ratingView=[[UIImageView alloc] initWithFrame:CGRectMake(0,0,30, 35)];
    textLabel=[[UILabel alloc] initWithFrame:CGRectMake(37,0, self.frame.size.width, self.frame.size.height-9)];
    //[textLabel setBackgroundColor:[UIColor redColor]];
    textLabel.textAlignment=UITextAlignmentLeft;
    //textLabel.text=@"sample";
    [textLabel setFont:[UIFont boldSystemFontOfSize:18]];
    [ratingView setImage:[UIImage imageNamed:@"Rating.png"]];
    [self addSubview:textLabel];
    [self addSubview:ratingView];
    [textLabel setTextColor:[UIColor blackColor]];
    [textLabel setHighlightedTextColor:[UIColor whiteColor]];
    imageChanged=NO;
    chaptersTableView=tableview;
    row=cellRow;
    section=cellSection;
    return self;
    - (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    // Configure the view for the selected state
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    NSLog(@"I m inside touches began method");
    for ( UITouch *touch in touches )
    CGPoint touchPoint = [touch locationInView:self];
    CGRect imageRect = CGRectMake(0, 0, 40, self.frame.size.height);
    if ( CGRectContainsPoint(imageRect, touchPoint) )
    NSLog(@"I have clicked on imageview");
    else
    //[self setBackgroundColor:[UIColor colorWithRed:2.0/255.0 green:114.0/255.0 blue:237.0/255.0 alpha:1.0]];
    //[self.textLabel setBackgroundColor:[UIColor colorWithRed:2.0/255.0 green:114.0/255.0 blue:237.0/255.0 alpha:1.0]];
    NSLog(@"I have clicked on tableView");
    - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
    //NSLog(@"I am inside touches cancelled");
    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
    @try
    for ( UITouch *touch in touches )
    CGPoint touchPoint = [touch locationInView:self];
    CGRect imageRect = CGRectMake(0, 0, 40, self.frame.size.height);
    if ( CGRectContainsPoint(imageRect, touchPoint) )
    // NSLog(@"I have clicked on imageview");
    if(!imageChanged)
    //[_imageViewTarget performSelector:changeImageAction];
    [self.ratingView setImage:[UIImage imageNamed:@"Rating-filled.png"]];
    [self setImageChanged:YES];
    else
    [self.ratingView setImage:[UIImage imageNamed:@"Rating.png"]];
    [self setImageChanged:NO];
    else
    NSIndexPath *newSetRow = [NSIndexPath indexPathForRow:row inSection:section];
    [chaptersTableView selectRowAtIndexPath:newSetRow animated:NO scrollPosition:UITableViewScrollPositionNone];
    //[chaptersTableView selectRowAtIndexPath:<#(NSIndexPath *)indexPath#> animated:<#(BOOL)animated#> scrollPosition:<#(UITableViewScrollPosition)scrollPosition#>
    [_imageViewTarget performSelector:changeImageAction];
    //NSLog(@"I have clicked on tableView");
    //NSLog(@"I m inside touches ended ");
    @catch (NSException *ex) {
    NSLog(@"Exception caught %@",[ex description]);
    -(void)setImageViewTarget:(id)target action:(SEL)action
    _imageViewTarget=target;
    changeImageAction=action;
    -(void)checkImage
    if(self.imageChanged)
    NSLog(@"imchan %@",self);
    //NSLog(@"I m going to change the filled image");
    [self.imageView setImage:[UIImage imageNamed:@"Rating-filled.png"]];
    else
    NSLog(@"imnotch %@",self);
    ////////////// my view controller
    - (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
    cell=(CustomTableCell*)[tv dequeueReusableCellWithIdentifier:[NSString stringWithFormat:@"Identifier for row %d in section %d",indexPath.row,indexPath.section]];
    if(cell==nil)
    //cell=[[[CustomTableCell alloc] initWithFrame:CGRectZero reuseIdentifier:[NSString stringWithFormat:@"Identifier for row %d in section %d",indexPath.row,indexPath.section] tableView:tv] autorelease];
    cell=[[[CustomTableCell alloc] initWithFrame:CGRectZero reuseIdentifier:[NSString stringWithFormat:@"Identifier for row %d in section %d",indexPath.row,indexPath.section] tableView:tv cellRow:indexPath.row cellSection:indexPath.section]autorelease];
    //cell=[[[CustomTableCell alloc] initWithFrame:CGRectZero reuseIdentifier:[NSString stringWithFormat:@"Identifier for row %d in section %d",indexPath.row,indexPath.section]] autorelease];
    NSLog(@"** %d sec %d ** %@",[indexPath row],[indexPath section],cell);
    [cell setImageViewTarget:self action:@selector(changeImageView)];
    NSLog(@"%d***",cell.frame.size.height);
    @try {
    if(searchResults)
    [cell.textLabel setText:[searchResultArray objectAtIndex:indexPath.row]];
    else
    switch (indexPath.section) {
    case 0:
    [cell.textLabel setText:[[nameDictionary objectForKey:@"a"] objectAtIndex:indexPath.row]];
    break;
    case 1:
    [cell.textLabel setText:[[nameDictionary objectForKey:@"b"] objectAtIndex:indexPath.row]];
    break;
    case 2:
    [cell.textLabel setText:[[nameDictionary objectForKey:@"c"] objectAtIndex:indexPath.row]];
    break;
    default:
    break;
    @catch (NSException *ex ){
    NSLog(@"Exception caught %@",[ex description]);
    //if(indexPath.row<10)
    // [cell.textLabel setText:[NSString stringWithFormat:@"sample %d in section %d",indexPath.row,indexPath.section]];
    [cell checkImage];
    [cell setImageViewTarget:self action:@selector(changeImageView)];
    //cell.selectionStyle=UITableViewCellSelectionStyleBlue;
    return cell;
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    NSLog(@"I am inside did select row at index path");
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    //[tableView getHeaderView];
    if(searchResults)
    return 1;
    return 3;
    - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
    if(searchResults)
    return [[[searchResultArray objectAtIndex:0] capitalizedString] substringToIndex:1];
    else
    if(section==0)
    //[tableView getHeaderView];
    return @"A";
    else if(section==1)
    //[tableView getHeaderView];
    return @"B";
    else if(section==2)
    //[tableView getHeaderView];
    return @"C";
    return @"";
    - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
    return [NSArray arrayWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@" M",@"N",@"O",@"P",nil];
    -(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
    //NSLog(@"i m inside touches began method");
    -(void)changeImageView
    //NSIndexPath *newSetRow = [NSIndexPath indexPathForRow:2 inSection:0];
    //[mTableView selectRowAtIndexPath:newSetRow animated:NO scrollPosition:UITableViewScrollPositionNone];
    NSLog(@"I m inside changeImageView");
    SampleViewController *sample=[[SampleViewController alloc] init];
    [self.navigationController pushViewController:sample animated:NO];
    //[cell.ratingView setImage:[UIImage imageNamed:@"Rating-filled.png"]];
    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    return 36;
    }

  • UITableViewCell and the Interface Builder

    I'm trying to use the Interface Builder to create a UITableViewCell but am having problems.
    I can create the UITableViewClass in my .xib file, connect the reference outlet and reuseIdentifier using the inspector. The problems occurs when I try and render the cell with this method...
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    Since the interface builder creates the TableViewCell automatically, I should be able to call...
    UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"priceCell"] autorelease];
    ..from inside the tableView:cellForRowAtIndexPath method and get that cell instance. But none of changes (Color, accessory view, etc...) I made to the table view come through.
    Has anyone got UITableViewCells created in the interface builder to work?

    Just an update to inform people of some of my findings.
    I had originally, before gkstuart's post, had added a UITableViewCell instance as a child of my view in IB. I then tried to use the cell via an IBOutlet in the UITableView in my view. This is when I was getting a completely blank screen when running my application. I then adopted gkstuart's idea and created a cell factory class, but without thinking, I used the same cell instance on each call to my 'newCell' method. Once I updated the 'newCell' method to load the nib file on each call to 'newCell' everything seems to work fine. As a note, the nib file loaded by 'newCell' is a simple nib file containing only my custom cell definition. It does not contain any views. Gkstuart's method of loading custom cells is unfortunate, because you can't seem to use the reusable cell theory when working with cells defined in IB. This is obviously something that needs work on Apple's side.
    As a test, I removed my custom cell definition from my original view nib. I then added a new top level instance of UITableViewCell, by dragging the UITableViewCell item to the window with the File Owner icon. After updating the custom cell definition with the appropriate class and outlets, I tried my original method again. I no longer get a completely blank screen, but it still doesn't work right. I now get a single cell in my table view, which happens to be the last cell in the list. When looking at it with the debugger, dequeueReusableCell never returns my cell instance so I am reusing and returning the same cell for each call to 'cellAtIndexPath'. I tried to manually call the cells 'prepareForReuse' method but this didn't seem to have any affect.
    So at this point, I am going to continue with the cell factory methodology until Apple either fixes the current problem or informs people on the proper way to use IB with custom UITableViewCell's.
    As a side note, I am going to start blogging about my experiences with the iPhone SDK over at iphonesdktrialsandtribulations.blogger.com.

  • Xcode IB Window Problem

    Hello,
    im new to Xcode and have (i think) a simple question. I want to open a new window by pressing a simple push button. I know how to do that. My problem is, that i want to bind it to a condition. When i press a button, there should be a check: for example if textfield 1 = "test123" and textfield 2 = password, then open window x.
    So im just missing the command for opening a window

    This is for iOS but the idea should be similar for OS X:
    .h
    @interface myViewController : UIViewController <UITextFieldDelegate>
        UITextField *aTextField;
    -(void)buttonPressed;
    @property (nonatomic, retain) UITextField *state;
    .m
    @implementation myViewController
    @synthesize aTextField;
    -(void)loadView
        UIView *view = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"An Image.png"]];
        self.view = view;
        [view release];
        self.view.frame = CGRectMake(114, 212, 540, 620);
        aTextField = [[UITextField alloc] initWithFrame:CGRectMake(70, 230, 80, 22)];
       [self.view addSubview:aTextField];
       self.view.userInteractionEnabled = YES;

  • Do I need to release UITableViewCell accessoryView in my iPhone app?

    The memory management documentation says I need to release objects I create with alloc.
    In my case I am creating a custom view (a UIButton) using alloc and assigning to the cell.accessoryView. If I use a temporary object, I need to release it after making the assignment, that I understand, but do I need to include [cell.accessoryView release] somewhere too? Am I still responsible to release the button I've created? If not, why is that?
    None of the examples I can find in the Table Programming Guide address this one way or the other.

    Hi, you must not release it a second time with
    [cell.accesoryView release];
    // create a UIButton. Retaincount = 1
    button = [[UIButton alloc] initWithFrame:CGRectMake(270, 10, 25, 25)];
    // use it as accessoryView (retaincount will be increased by 1)
    cell.accessoryView = button;
    // release the button. (retaincount will be decreased by 1 back to 1)
    [button release];
    if you want to "get rid" of the accessoryView in that cell later you just need to
    cell.accessoryView = nil;
    This will cause the cell to release the button which drops the retaincount to 0

  • Non-English's bold font problem

    I want to set the label's font by bold.
    This is the part of my code.
    UIFont* font = [UIFont boldSystemFontOfSize: 20];
    UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 50)]];
    label.font = font;
    label.text = @"ようこそ";
    If text is english, it draws rightly by bold.
    But text is non-engligh such as Japanese, Korean, it doesn't work by bold.
    Is there any way?

    It's entirely possible that those languages simply don't do bold text in the same way that Chinese doesn't do capital and lowercase letters. Perhaps you could switch typefaces or something instead.

  • (iPhone SDK 7) UIScrollView subview touch problem

    New here, in fact new to the SDK but getting on well with it (plenty of previous coding experience to draw on). However, I've been hitting my head against a brick wall with UIScrollView and it making subviews, e.g. UIImageViews, no longer be touchable. When I move the image views outside the scroll view it's fine, so I know they're working and the touchesBegan:withEvent is processing as it should do.
    Here's what I'm doing in the initWithFrame:
    scroller = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0,320,400)];
    scroller.scrollEnabled = YES;
    CGSize sz;
    sz.width = 320;
    sz.height = 800;
    scroller.contentSize = sz;
    scroller.tag = 400;
    scroller.userInteractionEnabled = YES;
    scroller.delaysContentTouches = YES;
    scroller.canCancelContentTouches = NO;
    [self addSubview:scroller];
    (I've tried all different combinations of delaysContentTouches and canCancelContentTouches just to see if they made a difference, originally I hadn't got either in there. But they don't seem to alter anything)
    And then the image views:
    buttonPlay = [[UIImageView alloc] initWithFrame:CGRectMake(20,320,40,40)];
    buttonPlay.image = [UIImage imageNamed:@"blah.jpg"];
    buttonPlay.userInteractionEnabled = YES;
    buttonPlay.tag = 100;
    [scroller addSubview:buttonPlay];
    buttonSettings = [[UIImageView alloc] initWithFrame:CGRectMake(80,320,40,40)];
    buttonSettings.image = [UIImage imageNamed:@"blah.jpg"];
    buttonSettings.userInteractionEnabled = YES;
    buttonSettings.tag = 101;
    [scroller addSubview:buttonSettings];
    Basically no touch events are being generated anywhere I click within the scroll view and I'm at a loss to work out why.
    Not sure if it's related either but I can't get a UILabel to respond to a touch either, even though I've enabled userInteractionEnabled for it - even trying a simple project I can't get a UILabel to generate a touch event at all.
    Any help on the above scroll view issue would be appreciated as it's driving me nuts!
    Cheers

    UIScrollView must not pass these events up the responder chain. I'm not sure if this is intended behavior, but it seems like it might be (if so the docs should be updated). I took my test code and verified:
    1. scroller's nextResponder points the UIView of the ViewController.
    2. That UIView has a nextResponder pointing to the ViewController
    This is what you would expect from the docs on the UIResponder Chain. However, it relies on each UIView subclass to pass the event up the responder chain +if it isn't handled fully+. UIScrollView must be making the assumption that "the buck stops here". Hence your touchesBegan: in your viewController never gets the message.
    Further, a little more testing with this at the end of viewDidLoad:
    BOOL status1 = [scroller canResignFirstResponder];
    BOOL status2 = [scroller resignFirstResponder];
    BOOL status3 = [self.view becomeFirstResponder];
    showed me:
    status1 = NO
    status2 = NO
    status3 = NO
    I'd say UIScrollView likes the power it wields .

  • Couldn't parse image from XML file using NSXMLParser

    Hi all, Since i am newbie to developing iPhone application, i have problem in parsing XML data.
    I use the following code for parsing XML file, this is RootViewController.h file
    #import <UIKit/UIKit.h>
    #import "SlideMenuView.h"
    #define kNameValueTag 1
    #define kColorValueTag 2
    #define kSwitchTag 100
    @class DetailViewController;
    @interface RootViewController : UIViewController <UITableViewDataSource, UITableViewDelegate> {
    DetailViewController *detailViewController;
    UITableView *myTable;
    UIActivityIndicatorView *activityIndicator;
    UIButton *btn;
    CGSize cellSize;
    NSXMLParser *rssParser;
    NSMutableArray *stories;
    NSMutableDictionary *item;
    NSString *currentElement;
    NSMutableString *currentTitle, *currentDate, *currentSummary, *currentLink, *currentImage;
    SlideMenuView *slideMenu;
    NSMutableArray *buttonArray;
    UIButton *rubic;
    UIButton *buurt;
    UIButton *beeld;
    UILabel *lbl;
    NSString *url;
    @property (nonatomic, retain) UITableView *myTable;
    @property (nonatomic, retain) DetailViewController *detailViewController;
    @property (nonatomic, retain) SlideMenuView *slideMenu;
    @property (nonatomic, retain) UIButton *btn;
    @property (nonatomic, retain) NSMutableArray *buttonArray;
    @property (nonatomic, retain) UIButton *rubic;
    @property (nonatomic, retain) UIButton *buurt;
    @property (nonatomic, retain) UIButton *beeld;
    @property (nonatomic, retain) UILabel *lbl;
    @end
    below is the RootViewController.m file,
    #import <Foundation/Foundation.h>
    #import "RootViewController.h"
    #import "DetailViewController.h"
    #import "SlideMenuView.h"
    @implementation RootViewController
    @synthesize rubic, buurt, beeld, detailViewController, myTable, btn, buttonArray, slideMenu, lbl;
    - (void)parseXMLFileAtURL:(NSString *)URL {
    stories = [[NSMutableArray alloc] init];
    //you must then convert the path to a proper NSURL or it won't work
    NSURL *xmlURL = [NSURL URLWithString:URL];
    // here, for some reason you have to use NSClassFromString when trying to alloc NSXMLParser, otherwise you will get an object not found error
    // this may be necessary only for the toolchain
    rssParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
    // Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
    [rssParser setDelegate:self];
    // Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
    [rssParser setShouldProcessNamespaces:NO];
    [rssParser setShouldReportNamespacePrefixes:NO];
    [rssParser setShouldResolveExternalEntities:NO];
    [rssParser parse];
    - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
    NSString * errorString = [NSString stringWithFormat:@"Unable to download story feed from web site (Error code %i )", [parseError code]];
    NSLog(@"error parsing XML: %@", errorString);
    UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Error loading content" message:errorString delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [errorAlert show];
    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
    //NSLog(@"found this element: %@", elementName);
    currentElement = [elementName copy];
    if ([elementName isEqualToString:@"item"]) {
    // clear out our story item caches...
    item = [[NSMutableDictionary alloc] init];
    currentTitle = [[NSMutableString alloc] init];
    currentDate = [[NSMutableString alloc] init];
    currentSummary = [[NSMutableString alloc] init];
    currentLink = [[NSMutableString alloc] init];
    currentImage = [[NSMutableString alloc] init];
    - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
    //NSLog(@"ended element: %@", elementName);
    if ([elementName isEqualToString:@"item"]) {
    // save values to an item, then store that item into the array...
    [item setObject:currentTitle forKey:@"title"];
    [item setObject:currentSummary forKey:@"summary"];
    [item setObject:currentDate forKey:@"date"];
    [item setObject:currentImage forKey:@"enclosure"];
    [stories addObject:[item copy]];
    NSLog(@"adding story: %@", currentTitle);
    - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
    //NSLog(@"found characters: %@", string);
    // save the characters for the current item...
    if ([currentElement isEqualToString:@"title"]) {
    [currentTitle appendString:string];
    } else if ([currentElement isEqualToString:@"description"]) {
    [currentSummary appendString:string];
    } else if ([currentElement isEqualToString:@"pubDate"]) {
    [currentDate appendString:string];
    } else if ([currentElement isEqualToString:@"enclosure"]) {
    [currentImage appendString:string];
    - (void)parserDidEndDocument:(NSXMLParser *)parser {
    [activityIndicator stopAnimating];
    [activityIndicator removeFromSuperview];
    NSLog(@"all done!");
    NSLog(@"stories array has %d items", [stories count]);
    [myTable reloadData];
    - (void)loadView {
    //self.title = @"GVA_iPhone";
    //UIImage *img = [UIImage imageNamed: @"gva_v2.1.png"];
    CGRect frame = [[UIScreen mainScreen] bounds];
    UIView *aView = [[UIView alloc] initWithFrame:frame];
    aView.backgroundColor = [UIColor grayColor];
    self.view = aView;
    [aView release];
    lbl = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 33.0, 320.0, 30.0)];
    lbl.backgroundColor = [UIColor colorWithRed:21.0/255.0 green:113.0/255.0 blue:194.0/255.0 alpha:1.0];
    lbl.textColor = [UIColor whiteColor];
    lbl.font = [UIFont boldSystemFontOfSize:18.0];
    [self.view addSubview:lbl];
    [lbl release];
    buttonArray = [[NSMutableArray alloc] init];
    for(int i = 1; i < 4; i++)
    // Rounded rect is nice
    //UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    // Give the buttons a width of 100 and a height of 30. The slide menu will take care of positioning the buttons.
    // If you don't know that 100 will be enough, use my function to calculate the length of a string. You find it on my blog.
    [btn setFrame:CGRectMake(0.0f,3.0f, 120.0f, 30.0f)];
    switch(i){
    case 1:
    [btn setTitle:[NSString stringWithFormat:@" Snel", i+1] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:@"topbg02.png"] forState:UIControlStateNormal];
    lbl.text = @" Snel";
    [btn addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [buttonArray addObject:btn];
    break;
    case 2:
    [btn setTitle:[NSString stringWithFormat:@" Binnenland", i+1] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:@"topbg02.png"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [buttonArray addObject:btn];
    break;
    case 3:
    [btn setTitle:[NSString stringWithFormat:@" Buitenland", i+1] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:@"topbg02.png"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(buttonTouched:) forControlEvents:UIControlEventTouchUpInside];
    [buttonArray addObject:btn];
    break;
    [btn release];
    slideMenu = [[SlideMenuView alloc]initWithFrameColorAndButtons:CGRectMake(0.0, 3.0, 330.0, 30.0) backgroundColor:[UIColor blackColor] buttons:buttonArray];
    [self.view addSubview:slideMenu];
    UITableView *aTableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0, 63.0, 320.0, 310.0)];
    aTableView.dataSource = self;
    aTableView.delegate = self;
    aTableView.rowHeight = 120;
    self.myTable = aTableView;
    [aTableView release];
    [self.view addSubview:myTable];
    rubic = [[UIButton alloc]initWithFrame:CGRectMake(0.0, 370.0, 105.0, 50.0)];
    [rubic setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [rubic setBackgroundImage:[UIImage imageNamed:@"MOUSEOVER.png"] forState:UIControlStateNormal];
    [rubic addTarget:self action:@selector(buttonBinn:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:rubic];
    UILabel *lblRub = [[UILabel alloc]initWithFrame:CGRectMake(10.0, 385.0, 45.0, 12.0)];
    lblRub.text = @"Rubriek";
    lblRub.font = [UIFont boldSystemFontOfSize:11.0];
    lblRub.backgroundColor = [UIColor clearColor];
    lblRub.textColor = [UIColor whiteColor];
    [self.view addSubview:lblRub];
    UIImageView *imgCat = [[UIImageView alloc] initWithFrame:CGRectMake(58.0, 375.0, 39.0, 36.0)];
    imgCat.image = [UIImage imageNamed:@"category_icon.png"];
    [self.view addSubview:imgCat];
    buurt = [[UIButton alloc] initWithFrame:CGRectMake(105.0, 370.0, 108.0, 50.0)];
    [buurt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [buurt setBackgroundImage:[UIImage imageNamed:@"bottombg01.png"] forState:UIControlStateNormal];
    [buurt addTarget:self action:@selector(buttonBuurt:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buurt];
    UILabel *lblGlo = [[UILabel alloc]initWithFrame:CGRectMake(112.0, 385.0, 59.0, 12.0)];
    lblGlo.text = @"In de Buurt";
    lblGlo.font = [UIFont boldSystemFontOfSize:11.0];
    lblGlo.backgroundColor = [UIColor clearColor];
    lblGlo.textColor = [UIColor whiteColor];
    [self.view addSubview:lblGlo];
    UIImageView *imgGlo = [[UIImageView alloc] initWithFrame:CGRectMake(173.0, 375.0, 39.0, 36.0)];
    imgGlo.image = [UIImage imageNamed:@"globe_icon.png"];
    [self.view addSubview:imgGlo];
    beeld = [[UIButton alloc]initWithFrame:CGRectMake(213.0, 370.0, 108.0, 50.0)];
    [beeld setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [beeld setBackgroundImage:[UIImage imageNamed:@"bottombg01.png"] forState:UIControlStateNormal];
    [beeld addTarget:self action:@selector(buttonBeeld:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:beeld];
    UILabel *lblCam = [[UILabel alloc]initWithFrame:CGRectMake(228.0, 385.0, 45.0, 12.0)];
    lblCam.text = @"In Beeld";
    lblCam.font = [UIFont boldSystemFontOfSize:11.0];
    lblCam.backgroundColor = [UIColor clearColor];
    lblCam.textColor = [UIColor whiteColor];
    [self.view addSubview:lblCam];
    UIImageView *imgCam = [[UIImageView alloc] initWithFrame:CGRectMake(276.0, 375.0, 39.0, 36.0)];
    imgCam.image = [UIImage imageNamed:@"camera_icon.png"];
    [self.view addSubview:imgCam];
    if([stories count] == 0) {
    [self parseXMLFileAtURL:@"http://iphone.concentra.exuvis.com/feed/rss/article/2/binnenland.xml"];
    cellSize = CGSizeMake([myTable bounds].size.width,60);
    - (IBAction)buttonPressed:(id)sender {
    lbl.text = ((UIButton*)sender).currentTitle;
    - (IBAction)buttonClicked:(id)sender {
    lbl.text = ((UIButton*)sender).currentTitle;
    - (IBAction)buttonTouched:(id)sender {
    lbl.text = ((UIButton*)sender).currentTitle;
    -(void)buttonBinn:(id)sender
    [rubic setBackgroundImage:[UIImage imageNamed:@"MOUSEOVER.png"] forState:UIControlStateNormal];
    [buurt setBackgroundImage:[UIImage imageNamed:@"bottombg01.png"] forState:UIControlStateNormal];
    [beeld setBackgroundImage:[UIImage imageNamed:@"bottombg01.png"] forState:UIControlStateNormal];
    -(void)buttonBuurt:(id)sender
    [buurt setBackgroundImage:[UIImage imageNamed:@"MOUSEOVER.png"] forState:UIControlStateNormal];
    [beeld setBackgroundImage:[UIImage imageNamed:@"bottombg01.png"] forState:UIControlStateNormal];
    [rubic setBackgroundImage:[UIImage imageNamed:@"bottombg01.png"] forState:UIControlStateNormal];
    -(void)buttonBeeld:(id)sender
    [beeld setBackgroundImage:[UIImage imageNamed:@"MOUSEOVER.png"] forState:UIControlStateNormal];
    [rubic setBackgroundImage:[UIImage imageNamed:@"bottombg01.png"] forState:UIControlStateNormal];
    [buurt setBackgroundImage:[UIImage imageNamed:@"bottombg01.png"] forState:UIControlStateNormal];
    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
    - (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
    - (void)dealloc {
    [myTable release];
    [detailViewController release];
    [super dealloc];
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [stories count];
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GVAiPhone"];
    if (cell == nil) {
    //CGRect cellFrame = CGRectMake(0, 0, 300, 65);
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"GVAiPhone"] autorelease];
    //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    //cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow_icon.png"]];
    CGRect nameValueRect = CGRectMake(5, 5, 275, 35);
    UILabel *nameValue = [[UILabel alloc] initWithFrame:nameValueRect];
    nameValue.tag = kNameValueTag;
    nameValue.font = [UIFont fontWithName:@"Arial" size:15.0];
    nameValue.lineBreakMode = UILineBreakModeWordWrap;
    nameValue.numberOfLines = 2;
    [cell.contentView addSubview:nameValue];
    [nameValue release];
    CGRect colorValueRect = CGRectMake(5, 38, 275, 65);
    UILabel *colorValue = [[UILabel alloc] initWithFrame:colorValueRect];
    colorValue.tag = kColorValueTag;
    colorValue.font = [UIFont fontWithName:@"Arial" size:11.0];
    colorValue.textColor = [UIColor colorWithRed:130.0/255.0 green:135.0/255.0 blue:139.0/255.0 alpha:1.0];
    colorValue.lineBreakMode = UILineBreakModeWordWrap;
    colorValue.textAlignment = UITextAlignmentLeft;
    colorValue.numberOfLines = 6;
    [cell.contentView addSubview:colorValue];
    [colorValue release];
    // Set up the cell
    //cell.text = [theSimpsons objectAtIndex:indexPath.row];
    //cell.hidesAccessoryWhenEditing = YES;
    NSUInteger storyIndex = [indexPath row];
    NSDictionary *rowData = [stories objectAtIndex:storyIndex];
    UILabel *name = (UILabel *)[cell.contentView viewWithTag:kNameValueTag];
    name.text = [rowData objectForKey:@"title"];
    //name.lineBreakMode;
    //UIImage *image =[UIImage imageNamed: currentImage];imageWithContentsOfFile
    //image.size.width = 50;
    //iimage.size.height = 50;
    //cell.image = [UIImage imageNamed:currentImage];
    cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow_icon.png"]];
    UILabel *color = (UILabel *)[cell.contentView viewWithTag:kColorValueTag];
    color.text = [rowData objectForKey:@"summary"];
    return cell;
    @end
    - here the actual problem is the xml node <enclosure> contains images but in using the method "didEndElement" , it doesn't parse into the <enclosure> node. ya so please help me in parsing and getting the image.
    Waiting for your help !!
    -Sathiya

    Hi, how did you solve your problem in detail. I'm having the same problem with this rss-feed: www.spiegel.de/index.rss
    I cannot parse the url of the images. I'm looking forward to your answer.

  • Dynamic heightForRowAtIndexPath - not so dynamic now :(

    Developers,
    I have a tableview that increases its cell height based on the length of a UILabel drawn within the cell. The UILabel is populated from strings in a Plist.
    In the same view i also have 'viewsForHeaderInSection' and 'tableViewHeaders', both of these are cutomised UILabels and are also populated from a plist
    The code is adapted from the code found here.
    The problem i have is that the 'heightForRowAtIndexPath' is not responding to increase in UILabel Length, so the strings are being presented in the UILabel's, but the cells are not expanding to encompass them.
    I am left with the visual mess that I have been playing around with this for 4 hours and now i need some fresh, experienced eyes to look at this.
    I have posted my code below in the hope that somebody can see why it is not working
    as always, any comments/suggestions/solutions are welcome.
    with thanks,
    j
    #import "ClinicalConditionsDetailViewController.h"
    #import "Constants.h"
    #define FONT_SIZE 11.0f
    #define CELLCONTENTWIDTH 309.0f
    #define CELLCONTENTMARGIN 10.0f
    @implementation ClinicalConditionsDetailViewController
    @synthesize ItemChild, clinicalConditions;
    - (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor clearColor];
    UILabel *tableHeader = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 60)];
    tableHeader.backgroundColor = [UIColor clearColor];
    tableHeader.font = [UIFont boldSystemFontOfSize:20];
    tableHeader.textAlignment = UITextAlignmentCenter;
    tableHeader.textColor = [UIColor whiteColor];
    NSDictionary *state = [clinicalConditions objectAtIndex:0/(NSInteger)nil]>;
    NSString *text = [state objectForKey:@"title"];
    tableHeader.text = text;
    self.tableView.tableHeaderView = tableHeader;
    [tableHeader release];
    ///////////////////////////////////dynamic cell size tableview code//////////////////////////////////////
    // Customize the number of sections in the table view.
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [clinicalConditions count];
    // Customize the number of rows in the table view.
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
    NSString *text = [ItemChild objectAtIndex:[indexPath section]];
    CGSize constraint = CGSizeMake(CELLCONTENTWIDTH - (CELLCONTENTMARGIN * 2), 20000.0f);
    CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
    CGFloat height = MAX(size.height, 44.0f);
    return height + (CELLCONTENTMARGIN * 2);
    - (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
    UITableViewCell *cell;
    UILabel *label = nil;
    cell = [tv dequeueReusableCellWithIdentifier:@"Cell"];
    if (cell == nil)
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"Cell"] autorelease];
    label = [[UILabel alloc] initWithFrame:CGRectZero];
    [label setLineBreakMode:UILineBreakModeWordWrap];
    [label setMinimumFontSize:FONT_SIZE];
    [label setNumberOfLines:0];
    [label setFont:[UIFont systemFontOfSize:FONT_SIZE]];
    [label setTag:1];
    /*[[label layer] setBorderWidth:2.0f];*/
    [[cell contentView] addSubview:label];
    NSString *text = [[clinicalConditions objectAtIndex:[indexPath section]]objectForKey:NAME_KEY];
    CGSize constraint = CGSizeMake(CELLCONTENTWIDTH - (CELLCONTENTMARGIN * 2), 20000.0f);
    CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
    if (!label)
    label = (UILabel*)[cell viewWithTag:1];
    [label setText:text];
    [label setFrame:CGRectMake(CELLCONTENTMARGIN, CELLCONTENTMARGIN, CELLCONTENTWIDTH - (CELLCONTENTMARGIN * 2), MAX(size.height, 44.0f))];
    return cell;
    ////////////////////////////// code for ViewForHeaderInSection//////////////////////////////////////
    - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
    NSDictionary *state = [clinicalConditions objectAtIndex:section];
    NSString *text = [state objectForKey:@"Header"];
    UILabel *sectionHeader = [[[UILabel alloc] initWithFrame:CGRectMake(100, 100, 200, 40)] autorelease];
    sectionHeader.backgroundColor = [UIColor clearColor];
    sectionHeader.font = [UIFont boldSystemFontOfSize:16];
    sectionHeader.textAlignment = UITextAlignmentLeft;
    sectionHeader.textColor = [UIColor whiteColor];
    sectionHeader.text = text;
    return sectionHeader;
    - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 24;
    #pragma mark -
    #pragma mark Memory management
    - (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    // Relinquish ownership any cached data, images, etc that aren't in use.
    - (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
    - (void)dealloc {
    [ItemChild release];
    [clinicalConditions release];
    [super dealloc];
    @end
    Message was edited by: james_coleman01

    Hi James -
    I think we need to get some clarity on what part of your schema is stored in 'clinicalConditions' and what part is stored in 'ItemChild'. To do that, we first need to be clear on the schema. I.e. we need to know the exact data structure stored in your plist file. The most recent schema I've seen is this one from [Plist to TableHeader text - a warning message that needs to be solved!|http://discussions.apple.com/message.jspa?messageID=12246134#12246134], Sept 9:
    Root.........................................................(Array)
    ........item0................................................(Dictionary)
    ................DiseaseName..................................(string)
    ................ItemChild....................................(Array)
    .....................Item0...................................(Dictionary)
    .............................title...........................(String)
    .............................Diseaseinfo.....................(String)
    .............................TitleForHeaderinsection.........(String)
    Is this the schema that applies now? If so, it appears that only some of your code fits.
    Firstly, the usage of 'clinicalConditions' appears to be consistent with the value of the ItemChild key. I.e. it's an array of dictionaries, and dictionary 0 stores the title of the entire table. Moreover the usage in viewDidLoad seems to be consistent with the usage in tableView:cellForRowAtIndexPath: and tableView:viewForHeaderInSection: (except that the latter uses "Header" as the key which is named TitleForHeaderinsection in the schema).
    Thus, if we assume 'clinicalConditions' is loaded from the value of ItemChild (presumably the rows of the ClinicalConditionsDetailView table), the array seems consistent with your Sept 9 schema.
    That leaves the 'ItemChild' array, which (suspiciously) is only used in tableView:heightForRowAtIndexPath:. I can't find any node in the schema that fits the usage of 'ItemChild'. Consider this code:
    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *text = [ItemChild objectAtIndex:[indexPath section]];
    NSLog(@"text=%@", text); // <-- add logging here
    CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
    NSLog(@"size=%@", NSStringFromCGSize(size)); // <-- add logging here
    Apparently we believe 'ItemChild' points to an array of strings, and we send sizeWithFont::: to each of those strings to estimate the required cell height. But I can't find any array of strings in the schema (both of the arrays I see are arrays of dictionaries). So what's in the 'ItemChild' array? Where and how is it loaded? And why aren't we using the same strings to calculate height that we used to load the labels in tableView:cellForRowAtIndexPath:? If 'ItemChild' points to an array of short strings (obtained from someplace or another), it looks like tableView:heightForRowAtIndexPath: might always return 44 + 20. Is that what you're observing?
    I haven't built a test bed yet, and if you study the above carefully, maybe that won't be necessary. I'm guessing the 'ItemChild' array isn't loaded with the correct strings, and is unnecessary in any case. It looks like you need to use the NAME_KEY strings from the 'clinicalConditions' dictionaries to calculate the height in tableView:heightForRowAtIndexPath: (and btw, the height calculation in tableView:cellForRowAtIndexPath: looks correct but isn't useful; only the return from tableView:heightForRowAtIndexPath: will determine the height of each cell, and the height of each label will then track the cell height).
    Is that enough for you to fix the code? Give it a try, and see if you can put it together, ok?
    - Ray

Maybe you are looking for