简体   繁体   English

如何仅在UIButton中为标题的特定部分设置图像

[英]How to set image only for a certain part of title in UIButton

I have a UIButton that has a title. 我有一个带有标题的UIButton。 Consider it as Thu 20. There is an image which is set as the background for the button,this image is width resized and content mode is aspect fit.So it appears to the full button. 考虑它为Thu20。有一幅图像被设置为按钮的背景,该图像的宽度被调整了大小,内容模式适合了宽高比。因此它出现在完整按钮上。 My problem: I need the image only for the "20" part and not the entire "Thu 20". 我的问题:我只需要“ 20”部分的图像,而不需要整个“ Thu 20”的图像。 if you see the iPad calendar you will get the point. 如果您看到iPad日历,便会明白这一点。 How can i do it? 我该怎么做? Thanks 谢谢

Unless something like an attributed string has a functionality of putting a rectangle around some text I suggest you to create a custom view that handles this: 除非类似属性字符串的功能具有在某些文本周围放置矩形的功能,否则建议您创建一个可处理此问题的自定义视图:

You would need a view that excepts 2 strings, a normal one and the one in the rectangle. 您将需要一个除2个字符串之外的视图,一个是普通的字符串,另一个是矩形中的字符串。 Then insert a normal label, set the text, call sizeToFit. 然后插入一个普通标签,设置文本,调用sizeToFit。 Then add the second label and do the same as first but in the end place it right next to the first label. 然后添加第二个标签,并与第一个标签相同,但最后将其紧靠在第一个标签旁边。 Then add the image view onto the label respecting the labels dimensions. 然后根据标签尺寸将图像视图添加到标签上。 Then resize the whole view to fit all the views on it. 然后调整整个视图的大小以适合其上的所有视图。 Now you can add this custom label to a button or anywhere you want it... 现在,您可以将此自定义标签添加到按钮或所需的任何位置...

我宁愿建议您放置一个包含图像的图像,然后在图像顶部放置一个标签,并在其上加上“ 20”,然后将一个自定义的UIButton放置在没有backGround颜色的情况下,并将两者都放置在顶部

With a bit of work you could override one of these UIButton methods to place the image at the correct location. 通过一些工作,您可以覆盖这些UIButton方法之一,以将图像放置在正确的位置。 Using a method within UILabel to determine the coordinates of "20" would give the the location for the image. 使用UILabel的方法确定坐标“ 20”将给出图像的位置。

class UIButton {

    // these return the rectangle for the background (assumes bounds), the content (image + title) and for the image and title separately. the content rect is calculated based
    // on the title and image size and padding and then adjusted based on the control content alignment. there are no draw methods since the contents
    // are rendered in separate subviews (UIImageView, UILabel)

    open func backgroundRect(forBounds bounds: CGRect) -> CGRect

    open func contentRect(forBounds bounds: CGRect) -> CGRect

    open func titleRect(forContentRect contentRect: CGRect) -> CGRect

    open func imageRect(forContentRect contentRect: CGRect) -> CGRect
}

See Apple's Documentation under "Getting Dimensions" for more information about these methods. 有关这些方法的更多信息,请参见“获取尺寸”下的Apple 文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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