关于按钮(button)图文上下并存

为了适配APP的语言本地化,按钮设计需要图标和文字描述并存,避免使用带有文字的切图。本文介绍了一种通过代码控制实现uibutton上图标与文字并排显示的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

由于APP要语言本地化,icon下还要有文字描述,导致切图不能带上文字;只好代码去控制了。实现方式如下:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.backgroundColor = [UIColor clearColor];

    //设置图片
    UIImage *imageForButton = [UIImage imageNamed:@"icon_search"];
    [button setImage:imageForButton forState:UIControlStateNormal];

    //设置文字
    [button setTitle:LS(@"Search") forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:10];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(search) forControlEvents:UIControlEventTouchUpInside];
    button.frame = CGRectMake(-20, 0 , 44, 44);   //硬编码设置UIButton位置、大小

    //使图片和文字水平居中显示
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    //文字距离上边框的距离增加imageView的高度,距离左边框减少imageView的宽度,距离下边框和右边框距离不变
    [button setTitleEdgeInsets:UIEdgeInsetsMake(button.imageView.frame.size.height+2 ,-button.imageView.frame.size.width, -2.0,0.0)];
    //图片距离右边框距离减少图片的宽度,其它不边
    [button setImageEdgeInsets:UIEdgeInsetsMake(-8.0, 0.0,0.0, -button.titleLabel.bounds.size.width*1.5)];
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];

    self.navigationItem.rightBarButtonItem = barButtonItem;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值