0

I am developing an universal app for iOS so that I have to set label to center in UIToolBar. Please help me to do this.

The code I have implemented

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 250, 40)];
label.backgroundColor = [UIColor clearColor];
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:label];
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"dd-MM-yyyy  hh:mm a"];
NSDate *now = [[NSDate alloc] init];
NSString *dateString = [format stringFromDate:now];
label.text = dateString;
Community
  • 1
  • 1
Ravi Varma
  • 131
  • 1
  • 1
  • 10

4 Answers4

1

FirstViewController.h

@interface FirstViewController:UIVieWController
{
   UILable *justLabel;
}
@end  

In FirstViewController.m try The fallowing code .Here I am taking timer for displaying time on the UIToolbar

 @implementation FirstViewController

 -(void)viewDidLoad
    {
        UIToolbar *tool=[[UIToolbar alloc] initWithFrame:CGRectMake(0,372,   self.view.frame.size.width, 44)];  

        justLabel = [[UILabel alloc] initWithFrame:CGRectMake(35, 4, 250, 40)];
            justLabel.backgroundColor = [UIColor clearColor];
        [self.view addSubview:tool];
        [tool addSubview:justLabel];            

    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timer) userInfo:nil repeats:YES];  


     }

-(void)timer
{

       NSDateFormatter *format = [[NSDateFormatter alloc] init];
       [format setDateFormat:@"dd-MM-yyyy  hh:mm:ss a"];
       NSDate *now = [NSDate date];
       NSString *dateString = [format stringFromDate:now];
       justLabel.text=dateString;

}

@end
venkat
  • 762
  • 2
  • 8
  • 20
1

You have to add flexible space bar button items before and after the label, this will center the label in your toolbar.

The flexible space is one of the system items when creating UIBarButtonItems. When you set the items of your toolbar, it should be an array containing a flexible space, your label, and another flexible space.

jrturton
  • 118,105
  • 32
  • 252
  • 268
0

Set frame of label according to the view width....

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake((self.view.frame.size.width-250)/2, 0, 250, 40)];

here in (self.view.frame.size.width-250)/2 250 is your required label width.....

Venk
  • 5,949
  • 9
  • 41
  • 52
  • i change the following change but it dint work for me it dint takes x, y vales. – Ravi Varma Nov 24 '12 at 13:05
  • By setting page width i am able to achieve this task UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, (self.view.frame.size.width)-55, 20)]; – Ravi Varma Nov 24 '12 at 13:26
0

By setting page with i am

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, (self.view.frame.size.width)-55, 20)];

Ravi Varma
  • 131
  • 1
  • 1
  • 10