gpt4 book ai didi

ios - 带有 titleLabel 的 Swift 菱形 UIButton

转载 作者:行者123 更新时间:2023-11-29 06:00:22 26 4
gpt4 key购买 nike

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

最佳答案

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

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

关于ios - 带有 titleLabel 的 Swift 菱形 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54734868/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com