ios - 以编程方式将左右图像添加到 UIButton

标签 ios swift

我正在尝试将图像添加到 UIButton 的左侧和右侧。我进行了研究,虽然有很多解决方案,但我还没有找到适合我的解决方案。

我需要能够:

  1. 显示或隐藏一个或两个图标
  2. 根据其他地方的其他逻辑自定义图标的颜色
  3. 使内容居中

布局是: 外部填充 + 左侧图标 + 内部填充 + 标签 + 填充 + 右侧图标 + 右侧填充

enter image description here

这是我最接近的一次,但并没有满足所有条件。我有以下代码作为 UIButton 的扩展:

func leftImage(image: UIImage, padding: CGFloat, renderMode: UIImage.RenderingMode) {
    self.setImage(image.withRenderingMode(renderMode), for: .normal)
    contentHorizontalAlignment = .center
    let availableSpace = bounds.inset(by: contentEdgeInsets)
    let availableWidth = availableSpace.width - imageEdgeInsets.right - (imageView?.frame.width ?? 0) - (titleLabel?.frame.width ?? 0)
    titleEdgeInsets = UIEdgeInsets(top: 0, left: availableWidth / 2, bottom: 0, right: 0)
    imageEdgeInsets = UIEdgeInsets(top: 0, left: padding, bottom: 0, right: 0)
}

func rightImage(image: UIImage, padding: CGFloat, renderMode: UIImage.RenderingMode){
    self.setImage(image.withRenderingMode(renderMode), for: .normal)
    semanticContentAttribute = .forceRightToLeft
    contentHorizontalAlignment = .center
    let availableSpace = bounds.inset(by: contentEdgeInsets)
    let availableWidth = availableSpace.width - imageEdgeInsets.left - (imageView?.frame.width ?? 0) - (titleLabel?.frame.width ?? 0)
    titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: availableWidth / 2)
    imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: padding)
}

目前,我对这段代码遇到的问题是: 1.无法更改色调样式之外的图标颜色 2.渲染布局不正确 3. 我只能显示左侧或右侧图标,但不能同时显示

如果我调用 leftImage 方法,我会得到以下结果:

enter image description here

如果我调用 rightImage 方法,我会得到以下结果:

enter image description here

如果我同时打电话,我会得到:

enter image description here

如果不清楚,我提前道歉,我对这一切还是新手。

最佳答案

  1. can't change the icon colors outside of the tint style 2. rendering isn't laying out correctly 3. I can only get the left or the right icon to show but not both

嗯,1是因为您没有指定您希望该图像的渲染模式应该是.alwaysOriginal。 3 是因为一个按钮只有一张图像。

第二是因为你想做的事情很困难,因为你试图让框架做一些它不想做的事情。

如果我是你,我会放弃尝试让图标成为按钮的一部分,而只是将一行图标-按钮-图标作为三个单独的 View 。如果您真的想要将这一切变成一个按钮,则必须使用按钮的背景图像,将其实时绘制到正确的大小,以便包含所需的图标。

关于ios - 以编程方式将左右图像添加到 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57015233/

相关文章:

ios - 访问 PFObject 成员时解析 "unrecognized selector sent to instance"

ios - 无法在 iOS 11 中设置备用应用程序图标

ios - 自定义 UISearchbar 的 UITextfield - iOS

arrays - Swift - 数组不会保存元素

ios - Web View 未加载 url 请求且 URL 显示 nil

ios - 如何检查 iPhone X 浏览器中的元素?

arrays - swift 数组 : Cannot invoke 'append' with an argument list of type '(Int)'

swift - 如何使用 cryptojs 加密 AES 256 并快速解密

swift - 符合协议(protocol)时类型别名声明的冗余重复(第 2 部分)

swift - “Fatal error: Unexpectedly found nil while unwrapping an Optional value”是什么意思?