开发者社区 问答 正文

在UIButton标题上居中图片

有一个自定义UIButton,占了视图的四分之一,我想要在按钮标题上设置一张图片,居中设置。

代码:

CGRect imageFrame= CGRectMake(0, 0, 80, 80);
UIEdgeInsets imageInset = UIEdgeInsetsMake(0, 0, 30, 0);
UIEdgeInsets titleInset = UIEdgeInsetsMake(80, 0, 0, 0);

btnSideSettings = [UIButton buttonWithType:UIButtonTypeCustom];
btnSideSettings.frame = settingsFrame;
[btnSideSettings setImage:[UIImage imageNamed:@"btnSideSettings"] forState:UIControlStateNormal];
btnSideSettings.imageView.frame = imageFrame;
btnSideSettings.imageEdgeInsets = imageInset;
btnSideSettings.titleEdgeInsets = titleInset;
btnSideSettings.titleLabel.textAlignment = NSTextAlignmentCenter;
[btnSideSettings setTitle:@"Settings" forState:UIControlStateNormal];

结果:

screenshot

如果注释掉添加图片,标题就会居中。

请明白人指点一下,谢谢。

展开
收起
爵霸 2016-03-17 13:30:50 2217 分享 版权
1 条回答
写回答
取消 提交回答
  • 可以换种方式来实现 。我这里的方式是用UIImageView 来倒圆角实现 .注意这里要导入一个库

    #import <QuartzCore/QuartzCore.h>
    
    UIImage *image=[UIImage imageNamed:@"btnSideSettings"];
    UIImageView *imgView=[[UIImageView alloc] initWithImage:image];
    
    /////给imgView进行圆形遮罩
    imgView.layer.masksToBound=YES;  ////required
    imgView.layer.cornerRadius=imgView.frame.size.width/2;  /////radiu is a half of imageview's width

    如果在图片上有点击动作可用手势来实现 。

    2019-07-17 19:05:12
    赞同 展开评论
问答地址: