StudentX
StudentX

Reputation: 2496

Align button at centre of Button iOS

I have a button whose size may vary as per requirement. But I need the image that is set on it, to always remain at its centre.

The code I'm using right now is:

[pAddButton setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
    [pAddButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
    [pAddButton setContentMode:UIViewContentModeCenter];

However, when I increase the width of the button, the images stretches automatically. That is what I'm trying to prevent.

Upvotes: 0

Views: 923

Answers (6)

Ajith Renjala
Ajith Renjala

Reputation: 5152

Have you tried setting content mode of imageView to centre like this:

pAddButton.imageView.contentMode = UIViewContentModeCenter;

Upvotes: 1

G.P.Reddy
G.P.Reddy

Reputation: 556

Try this code image frame to the button

[image drawInRect:CGRectMake((self.frame.size.width/2) - (image.size.width/2), (self.frame.size.height / 2) - (image.size.height / 2), image.size.width, image.size.height)];

Upvotes: 1

GPR
GPR

Reputation: 91

Try this,

CGPoint centerImageView = imageView.center;

centerImageView = pAddButton.center;

ImageView.center = centerImageView;

Upvotes: 0

BoilingLime
BoilingLime

Reputation: 2267

Did you try to simply center the image by :

myImageView.center = pAddButton.center;

Upvotes: 0

Fawad Masud
Fawad Masud

Reputation: 12344

You can use setImage instesd of setBackgroundImage OR add image as subView on the button [button addSubView:imageView].

Upvotes: 0

fluidsonic
fluidsonic

Reputation: 4676

Set the image using setImage:forState: instead of setBackgroundImage:forState:.

If that doesn't help you could use imageEdgeInsets to reduce the image's width.

Upvotes: 0

Related Questions