user2090207
user2090207

Reputation: 45

UIButton set image and title

I use the following code to load an image is on the upper, lower half is the title of the button, but only the image, is this why? Have any good Suggestions please let us know, thank you

UIButton *myButton = [[UIButton alloc]initWithFrame:CGRectMake(160, 400, 73, 44)];

    [myButton setImage:[UIImage imageNamed:@"icon.png"] forState:UIControlStateNormal];
    [myButton setImageEdgeInsets: UIEdgeInsetsMake(0,0,22,0)];

    [myButton setTitle:@"test" forState:UIControlStateNormal];
    [myButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [myButton setTitleEdgeInsets: UIEdgeInsetsMake(22,10,0,10)];

    [self.view addSubview:myButton];

Upvotes: 3

Views: 10736

Answers (1)

Dhruvik
Dhruvik

Reputation: 982

you can achieve this effect by this way also.. Try this ::

UIButton *myButton = [[UIButton alloc]initWithFrame:CGRectMake(160, 400, 73, 55)];
UIImage *img = [UIImage imageNamed:@"icon.png"];
UIImageView *imgVw = [[UIImageView alloc ] init];
imgVw.image  = img;
imgVw.frame = CGRectMake(myButton.frame.origin.x, myButton.frame.origin.y, myButton.frame.size.width, (myButton.frame.size.height-18));
[myButton setTitle:@"test" forState:UIControlStateNormal];
[myButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[myButton setTitleEdgeInsets: UIEdgeInsetsMake(34,10,0,10)];
[myButton addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:imgVw];    
[self.view addSubview:myButton];

Your button method

-(void) btnClick:(id)sender
{
    NSLog(@"working");
}

You can achieve from your logic also :: Here i've edited some code in your logic

UIButton *myButton = [[UIButton alloc]initWithFrame:CGRectMake(160, 400, 40, 35)];
[myButton setImage:[UIImage imageNamed:@"icon.png"] forState:UIControlStateNormal];
[myButton setImageEdgeInsets:UIEdgeInsetsMake(0,(myButton.frame.size.width-52),17,0)];
[myButton setTitle:@"test" forState:UIControlStateNormal];
[myButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[myButton setTitleEdgeInsets: UIEdgeInsetsMake(22,(myButton.frame.size.width-78),0,22)];
[self.view addSubview:myButton];

but, in this logic you have to resize your image to 23*23 pixels. according to your image size UIEdgeInsetsMake's parameter will be changed.

Hope this helps. Happy coding.

Upvotes: 4

Related Questions