UIButton 没有为 .infoLight 显示 "i" 的圆圈

UIButton not showing the circle with "i" for .infoLight

出于某种原因,当我 运行 下面的函数以编程方式添加 UIButton(和我确实想以编程方式而不是在界面生成器中执行此操作)-我将其添加到 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", 对于: .normal)

问题

在使用 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. In the version below I use Layout Anchors to set the constraints. Advantages of auto layout you can find 之一。

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
}