菜鸟教程小白 发表于 2022-12-13 00:48:40

ios - 在 UIButton 上将图像的位置与标题的长度分开


                                            <p><p>UIButton 图像位置取决于同一图像的当前标题长度。</p>

<p>如果没有设置标题,则第一个 UIButton 图像居中。
当有一个时,第二个向左移动(“喜欢”)。</p>

<p> <img src="/image/BAr0z.png" alt="Thumb image is centered if there is no title set"/>
<img src="/image/aaNiY.png" alt="Thumb image is shifted to the right when a title is set"/> </p>

<p>如何始终将 UIButton 图像保持在按钮的中心?即使标题出现在它的顶部?</p>

<p>我已经尝试过使用 imageInset 并且是同样的问题。除了默认的 UIButton 之外,我还不想使用其他 UIImageView。</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>你可以使用下面的代码...</p>

<pre><code>// the space between the image and text
CGFloat spacing = 6.0;

// lower the text and push it left so it appears centered
//below the image
CGSize imageSize = button.imageView.frame.size;
button.titleEdgeInsets = UIEdgeInsetsMake(
0.0, - imageSize.width, - (imageSize.height + spacing), 0.0);

// raise the image and push it right so it appears centered
//above the text
CGSize titleSize = button.titleLabel.frame.size;
button.imageEdgeInsets = UIEdgeInsetsMake(
- (titleSize.height + spacing), 0.0, 0.0, - titleSize.width);
</code></pre>

<p>来源:<a href="https://stackoverflow.com/questions/2451223/uibutton-how-to-center-an-image-and-a-text-using-imageedgeinsets-and-titleedgei" rel="noreferrer noopener nofollow">UIButton: how to center an image and a text using imageEdgeInsets and titleEdgeInsets?</a> </p>

<p>您可以使用以下链接尝试替代解决方案</p>

<p> <a href="https://stackoverflow.com/questions/11717219/uibutton-image-text-ios" rel="noreferrer noopener nofollow">UIButton Image + Text IOS</a> </p>

<p>希望对你有帮助...</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 在 UIButton 上将图像的位置与标题的长度分开,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/25380637/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/25380637/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 在 UIButton 上将图像的位置与标题的长度分开