Ravi Varma
Ravi Varma

Reputation: 131

how to set label to center in uitoolbar

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;

Upvotes: 0

Views: 1475

Answers (4)

Ravi Varma
Ravi Varma

Reputation: 131

By setting page with i am

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

Upvotes: 0

jrturton
jrturton

Reputation: 119262

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.

Upvotes: 1

venkat
venkat

Reputation: 762

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

Upvotes: 1

Venk
Venk

Reputation: 5955

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.....

Upvotes: 0

Related Questions