出于某种原因,当我运行下面的函数以编程方式添加UIButton时,没有显示带有“i”的iOS按钮标准圈。(我确实希望以编程方式而不是在界面中执行此操作) builder) - 我将它添加到UIPageViewController。我在屏幕的左下方有一个按钮,我将它设置为.backgroundColor = .lightGray以验证它已被添加到子视图&工作正常(图片左侧,下方)。对我可能最基本的东西的想法?非常感谢!
func configureAboutButton() {
let aboutButtonHeight: CGFloat = 44
let aboutButtonWidth: CGFloat = 44
aboutButton = UIButton(type: .infoLight)
aboutButton.tintColor = UIColor.red
aboutButton = UIButton(frame: CGRect(x: 0, y: view.frame.height - aboutButtonHeight, width: aboutButtonWidth, height: aboutButtonHeight))
aboutButton.backgroundColor = .lightGray
aboutButton.addTarget(self, action: #selector(segueToAboutVC), for: .touchUpInside)
view.addSubview(aboutButton)
}
奇怪的是,如果我在设置背景颜色的下方添加此行,则右侧的图像显示(否则我会在左侧显示图像)。
aboutButton.setTitle(“X”,for:。normal)
答案 0 :(得分:1)
使用aboutButton = UIButton(type: .infoLight))
创建按钮后,再次使用aboutButton = UIButton(frame: CGRect(x: 0, y: view.frame.height - aboutButtonHeight, width: aboutButtonWidth, height: aboutButtonHeight))
创建按钮。这就是为什么信息图标没有显示。
只需设置框架属性aboutButton.frame = CGRect(x: 0, y: view.frame.height - aboutButtonHeight, width: aboutButtonWidth, height: aboutButtonHeight)
即可设置按钮的框架,然后删除aboutButton = UIButton(frame: CGRect(x: 0, y: view.frame.height - aboutButtonHeight, width: aboutButtonWidth, height: aboutButtonHeight))
:
func configureAboutButton() {
let aboutButtonHeight: CGFloat = 44
let aboutButtonWidth: CGFloat = 44
aboutButton = UIButton(type: .infoLight)
aboutButton.tintColor = UIColor.red
aboutButton.frame = CGRect(x: 0, y: view.frame.height - aboutButtonHeight, width: aboutButtonWidth, height: aboutButtonHeight)
aboutButton.backgroundColor = .lightGray
aboutButton.addTarget(self, action: #selector(segueToAboutVC), for: .touchUpInside)
view.addSubview(aboutButton)
}
更好的解决方案是使用auto layout options to set constraints programmatically之一。在下面的版本中,我使用布局锚点来设置约束。例如,您可以找到here自动布局的优点。
func configureAboutButton() {
aboutButton = UIButton(type: .infoLight)
// need to set to false, to set the constraints programmatically
aboutButton.translatesAutoresizingMaskIntoConstraints = false
aboutButton.tintColor = UIColor.red
aboutButton.backgroundColor = .lightGray
aboutButton.addTarget(self, action: #selector(segueToAboutVC), for: .touchUpInside)
view.addSubview(aboutButton)
// set the constraints via Layout Anchors
// x, y, w, h
aboutButton.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
aboutButton.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
aboutButton.widthAnchor.constraint(equalToConstant: 44).isActive = true
aboutButton.heightAnchor.constraint(equalToConstant: 44).isActive = true
}