首页 > 解决方案 > 带有titleLabel的Swift菱形UIButton

问题描述

我想在 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
}()

标签: iosswiftuibutton

解决方案


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

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,您可以使用约束,如果按钮是方形的,它看起来最好(但您可以再次使用内部菱形的约束来修复它)


推荐阅读