简体   繁体   中英

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.

将此代码图像框尝试到按钮

[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)];

您是否尝试过将imageView的内容模式设置为居中,例如:

pAddButton.imageView.contentMode = UIViewContentModeCenter;

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.

您可以使用setBackgroundImage的setImage instesd或在按钮[button addSubView:imageView]上将图像添加为subView。

您是否尝试通过以下方式简单地将图像居中:

myImageView.center = pAddButton.center;

Try this,

CGPoint centerImageView = imageView.center;

centerImageView = pAddButton.center;

ImageView.center = centerImageView;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM