我正在尝试将图像添加到 UIButton 的左侧和右侧。我进行了研究,虽然有很多解决方案,但我还没有找到适合我的解决方案。
我需要能够:
- 显示或隐藏一个或两个图标
- 根据其他地方的其他逻辑自定义图标的颜色
- 使内容居中
布局是: 外部填充 + 左侧图标 + 内部填充 + 标签 + 填充 + 右侧图标 + 右侧填充
这是我最接近的一次,但并没有满足所有条件。我有以下代码作为 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 方法,我会得到以下结果:
如果我调用 rightImage 方法,我会得到以下结果:
如果我同时打电话,我会得到:
如果不清楚,我提前道歉,我对这一切还是新手。
最佳答案
- 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/