ios - 带有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
}()
解决方案
为什么要旋转按钮?您可以在标题标签下插入视图,并使其大小相同并在按钮内居中,但被旋转。
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,您可以使用约束,如果按钮是方形的,它看起来最好(但您可以再次使用内部菱形的约束来修复它)
推荐阅读
- mysql - SequelizeDatabaseError:无法读取未定义的属性“解析”
- sql - 在 Postgresql 插入查询中获取“错误:在或附近出现语法错误”
- reactjs - 在自定义钩子中设置多个状态
- git - Git 在几次拉取后应用一些修改
- kubernetes - kubectl - 如何在 Kubernetes 中检索默认标签的值?
- electron - 如何在 Electron 应用程序中禁用网络?
- firebase - Flutter Firestore 地理查询距我的位置一定距离
- angular - Angular:用于注入依赖的自定义装饰器(@Inject 包装器)
- python - 获取字典的某些部分
- excel - Excel,使用从 Web 获取数据,我的 URL 参数之一被忽略