【问题标题】:When I create image for button the title for the button is not shown anymore?当我为按钮创建图像时,按钮的标题不再显示?
【发布时间】:2018-03-13 18:42:16
【问题描述】:
button.setTitle("Like", for: .normal)
button.setTitleColor(UIColor.rgb(red: 143, green: 150, blue: 163), for: .normal)
button.setImage(UIImage(named:"like"), for: .normal)
button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 8 , bottom:0, right: 0)
button.imageView?.contentMode = .scaleAspectFit

addConstraintsWithFormat(format: "H:|[v0]|", views: likeButton)
addConstraintsWithFormat(format: "V:|[v0(44)]|", views:likeButton)

如果我删除“button.setImage(UIImage(named:"like"), for: .normal)”行,那么标题会正确显示。如何同时显示标题和图像?

【问题讨论】:

  • 您的边缘插图最有可能导致标题消失。边缘插图 40 非常极端!
  • 还是不行
  • 实际图像有多大?
  • 是375*360像素
  • 那是相当大的。按钮会在屏幕上接近那个尺寸吗?尝试将图像设置为您想要的确切尺寸。

标签: ios swift swift3 uibutton uiimage


【解决方案1】:

创建 UIButton 的子类并覆盖

class MyButton : UIButton {
    override func titleRect(forContentRect contentRect: CGRect) -> CGRect {
        return CGRect(x: 0, y: self.bounds.size.height/2, width: self.bounds.size.width/2, height: self.bounds.size.height)
    }
    
    override func imageRect(forContentRect contentRect: CGRect) -> CGRect {
        return CGRect(x: (self.bounds.size.width/2 + 5), y: self.bounds.size.height/2, width: (self.bounds.size.width/2 - 5), height: self.bounds.size.height)
    }
}

为标题和图像计算的矩形是相对于 UIButton 的边界的,因此无论 UIButton 采用什么大小,它们都会根据计算进行调整以匹配它们的大小。

在下面的图片中 abcd 是标题,你在右侧看到的是按钮标题图像。

陷阱

UIButtons 尊重固有尺寸,这意味着它们将采用标题和标题图像叙述的尺寸,除非它们有足够的自动布局约束直接/间接决定它们的框架。

如果您将一个巨大的图像设置为按钮标题或将一个非常小的图像设置为按钮标题图像,您可能会分别看到一个非常大或非常小的按钮,除非您有宽度和高度或尾随、前导和顶部、底部约束。

因为标题和图像矩形是相对于 Button 的边界计算的,因此确保您有足够的约束来正确决定按钮的大小或确保您有完美尺寸的图像以确保按钮合适,这一点非常重要大小。

愉快的编码

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-26
    • 2021-01-24
    • 2013-05-20
    • 1970-01-01
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多