UIButton 图像位置取决于 titleLabel 的框架 [英] UIButton image position depends on the frame of titleLabel

查看:25
本文介绍了UIButton 图像位置取决于 titleLabel 的框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题很简单,但我找不到解决方案.我有一个带有标题和图像的 UIButton.无论发生什么,我都希望图像位置是固定的,所以我这样设置:

My issue is pretty simple yet I can't find a solution. I have a UIButton which has a title and image. I want image position to be fixed no matter what happens so I set it this way:

[button setImageEdgeInsets:UIEdgeInsetsMake(0.f, 0.f, 0.f, IS_IPHONE ? 20.f : 60.f)];

我没有为按钮的 titleLabel 设置任何位置.

I do not set any position for the button's titleLabel.

接下来发生的是我为按钮设置新标题,标题标签缩小或扩展以适应新文本,令人惊讶的是它使图像移动,所以很明显,尽管应用了图像边缘插入,图像位置取决于标签的框架.我看到了两种可以使用的解决方案:

What happens next is I set new title for the button, the title label shrinks or expands to fit new text and surprisingly it makes the image move, so it is obvious that despite applied image edge insets the image position depends on the label's frame. I see two solutions that can be used:

1) 使图像独立于标签的框架

1) Make image independent of label's frame

2) 为标签设置固定大小

2) Set fixed size for the label

但我不知道如何实现它们.你能给我一些建议,我该如何解决这个问题?

but I don't know how to implement neither of them. Can you please give me some advice how do I resolve this issue?

推荐答案

您可以子类化 UIButton 并管理图像 & rects标题.覆盖下面的方法并为图像和返回适当的矩形标题根据您的要求.

You can subclass UIButton and manage rects for image & title. Override below methods and return appropriate rects for image & title as per your requirement.

-(CGRect)imageRectForContentRect:(CGRect)contentRect;

-(CGRect)titleRectForContentRect:(CGRect)contentRect;

这篇关于UIButton 图像位置取决于 titleLabel 的框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆