我想在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
}()
答案 0 :(得分:0)
为什么要旋转按钮?您可以在标题标签下插入视图,并使其具有相同的大小,并在按钮中居中,但可以旋转。
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比按钮大一点的话,可以使用约束条件,如果按钮是方形的,则效果最好(但是您可以再次使用内部菱形的约束条件对其进行修复)