我正在尝试向 UIView
子类添加多个按钮。在 UIView
子类(称为 leftPanel
)的 init()
方法中,我添加了对不同函数的多个调用来添加每个按钮。这就是我的 init()
的样子:
override init(frame: CGRect){
super.init(frame: frame)
components = self.setupView()
print("Checkpoint: [leftPanel] init() call finished") // basic debug checkpoint
}
init()
调用名为 setupView()
的函数,其中包含对创建按钮的每个函数的调用。这是我的 setupView()
代码:
func setupView() -> [UIView] {
let addButton = self.setupAddButton()
let infoButton = self.setupInfoButton()
let orderPromoteButton = self.setupOrderPromoteButton()
let orderDemoteButton = self.setupOrderDemoteButton()
let refreshItemsButton = self.setupRefreshItemsButton()
let components = [lessonActionsLabel, addButton, infoButton, orderPromoteButton, orderDemoteButton, refreshItemsButton]
return components
}
setupView 函数中的每个调用都是一个较小的函数,其中包含将每个按钮添加到 leftPanel 子类的代码。我已经这样做了,这样我就可以根据需要删除每个成员,并且可以使用每个单独的设置功能根据需要将每个单独的项目重新添加到我的 View 中。大多数功能几乎相同,并使用以下代码:
func setupRefreshItemsButton() -> UIButton {
let refreshItemsButton = UIButton(type: UIButtonType.infoLight)
refreshItemsButton.frame = CGRect(x:0, y:screenHeight*55/100, width: screenWidth*30/100, height: screenHeight*5/100)
refreshItemsButton.setTitle(" Refresh lesson items", for: UIControlState.normal)
refreshItemsButton.setImage(UIImage(contentsOfFile: "up.png"), for: UIControlState.normal)
self.addSubview(refreshItemsButton)
return refreshItemsButton
}
设置每个按钮。然而,当我在 iOS 模拟器上运行它时,应该为每个按钮设置图像的行似乎不起作用。当我初始化每个按钮时,我使用 UIButtonType.infoLight
类型来初始化它们,因为我想使用与普通 infoLight
按钮相同的样式(例如文本颜色) 。我想要更改的 infoLight
类型的唯一属性是它旁边的图像(默认情况下是 (i))。我想将图标制作成 UIImage(contentsOfFile: "up.png")
,但它似乎不起作用。 请问有人可以建议我可以做出任何改变来实现这一目标吗?
我目前尝试对我所拥有的进行一些更改,例如将类型更改为 .custom
,看看这是否会改变图像,但这也不起作用。它仅重置我想使用的 .infoLight
的格式,因此我已将其切换回来。但是,如果您的解决方案要求我将其改回 .custom
,那么我可以做到。
我还尝试更改代码以仅使用 up
替换 up.png
,但它仍然不起作用。
我的代码都没有引发任何警告或错误。
编辑:大多数答案都建议我将 UIImage(contentsOfFile: "")
更改为 UIImage(named: "")
,我已经完成了,但它占据了 UIButton 的整个框架,我想更改它,并通过保留与 .infoLight
相同的内容右侧带有标签的小图像。任何人都可以建议一个解决方法吗?
这个问题的独特是什么?:虽然 .setImage() 已经通过使用 UIImage(named:)
解决了UIImage(contentsOfFile:)
的,我还想将 .setTitle()
标签保留在按钮对象中。 UIImage(named:)
调用使图像填充按钮的整个框架,但我想保持它与 .infoLight< 相同
,带有标题的小图像位于右侧。
最佳答案
使用背景图片,如下所示:
refreshItemsButton.setBackgroundImage(
UIImage(named:"up.png"),
for:UIControlState.normal)
关于ios - UIButton .setImage() 在 Swift 3 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45518982/