【问题标题】:Swift diamond shaped UIButton with titleLabel带有titleLabel的Swift菱形UIButton
【发布时间】:2019-07-11 02:30:35
【问题描述】:

我想在 Swift 中创建一个带有 titleLabel 的菱形 UIButton。我的问题是,titleLabel 文本缩小并且只显示三个点。如何扩展 titleLabel 的框架以获得足够的标题空间?

这是我的代码(宽度和高度为 70 磅)。

private let diamondButton: UIButton = {
    let button = UIButton()
    button.translatesAutoresizingMaskIntoConstraints = false
    button.setTitleColor(.white, for: .normal)
    button.setTitle("More", for: .normal)
    button.backgroundColor = .red
    button.layer.cornerRadius = 10
    button.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi / 4))
    button.titleLabel?.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi / -4))
    button.titleLabel?.textAlignment = .center
    button.titleLabel?.backgroundColor = .blue // Just for demonstration
    button.titleLabel?.bounds = button.frame
    button.titleLabel?.layer.masksToBounds = true
    button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
    return button
}()

【问题讨论】:

  • by button.adjustsFontSizeToFitWidth = true 你可以调整按钮内的字体大小,也许button.titleLabel?.clipsToBounds = falsebutton.minimumFontSize = 14 可以解决你的问题
  • 感谢您的回复阿拉什。不幸的是,它并没有解决问题。我试过:``` button.titleLabel?.clipsToBounds = true button.titleLabel?.adjustsFontSizeToFitWidth = true ```
  • 如果你设置了button.titleLabel?.clipsToBounds = false,你也应该设置button.clipsToBounds = false,并且为了调整字体大小你不需要titleLabel
  • 还是不行。我还尝试将 UILabel 作为子视图添加到按钮,但这不是一个优雅的解决方案。
  • 问题是双旋转不是制作菱形按钮的正确方法。

标签: ios swift uibutton


【解决方案1】:

为什么要旋转按钮?您可以在标题标签下插入视图,使其大小相同并在按钮内居中,但被旋转。

private let diamondButton: UIButton = {
    let button = UIButton()
    button.translatesAutoresizingMaskIntoConstraints = false
    button.setTitleColor(.white, for: .normal)
    button.setTitle("More", for: .normal)
    button.backgroundColor = .clear
    button.titleLabel?.textAlignment = .center
    button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)

    let diamond = UIView(frame: button.bounds)
    diamond.translatesAutoresizingMaskIntoConstraints = false
    diamond.isUserInteractionEnabled = false // button will handle touches
    // Handle it gracefully without force unwrapping
    button.insertSubview(diamond, belowSubview: button.titleLabel!)
    diamond.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi / 4))
    diamond.backgroundColor = .red
    diamond.layer.cornerRadius = 10
    diamond.widthAnchor.constraint(equalTo: button.widthAnchor).isActive = true
    diamond.widthAnchor.constraint(equalTo: diamond.heightAnchor).isActive = true
    diamond.centerXAnchor.constraint(equalTo: button.centerXAnchor).isActive = true
    diamond.centerYAnchor.constraint(equalTo: button.centerYAnchor).isActive = true
    return button
}()

如果你需要比按钮大一点的 BGR,你可以使用约束,如果按钮是方形的,它看起来最好(但你可以再次使用内部菱形的约束来修复它)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-10
    • 2022-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 2023-04-02
    • 1970-01-01
    相关资源
    最近更新 更多