【发布时间】:2017-11-14 09:58:45
【问题描述】:
所以,我正在为我的应用程序制作简单的表单。我有两个按钮,允许用户选择是否要输入电子邮件或电话号码。我制作了 2 个看起来像 android 样式标签按钮的按钮。如下:
所以我为我的按钮制作了自定义类。代码如下:
@IBDesignable
class HC24Button: UIButton {
@IBInspectable var tabButtonBorderWidth: CGFloat = 1.0
@IBInspectable var borderWidth: CGFloat = 0{
didSet{
layer.borderWidth = borderWidth
}
}
@IBInspectable var borderColor: UIColor? {
didSet{
updateView()
}
}
@IBInspectable var cornerRadius: CGFloat = 0{
didSet{
layer.cornerRadius = cornerRadius
}
}
@IBInspectable var tabsButton : Bool = false{
didSet{
updateView()
}
}
func updateView(){
let border = CALayer()
let width = tabButtonBorderWidth
border.borderColor = borderColor?.cgColor
border.frame = CGRect(x: 0, y: frame.size.height - width, width: frame.size.width + 20, height: frame.size.height)
border.borderWidth = width
layer.addSublayer(border)
layer.masksToBounds = true
}
}
这是我的视图控制器上的代码:
@IBAction func PhoneTapped(_ sender: HC24Button) {
sender.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
sender.tabButtonBorderWidth = 4.0
sender.borderColor = HC24AppColors.Main
EmailButton.tabButtonBorderWidth = 1.0
EmailButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
EmailButton.borderColor = .lightGray
UserPhoneEmailTextField.text = "62"
UserPhoneEmailTextField.keyboardType = .numberPad
}
@IBAction func EmailTapped(_ sender: HC24Button) {
sender.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
sender.tabButtonBorderWidth = 4.0
sender.borderColor = HC24AppColors.Main
PhoneButton.tabButtonBorderWidth = 1.0
PhoneButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
PhoneButton.borderColor = .lightGray
UserPhoneEmailTextField.text = ""
UserPhoneEmailTextField.placeholder = "Alamat Email"
}
但这是我得到的结果:
我只想要一个带有彩色边框的按钮,例如开关。我该如何解决这个问题?
【问题讨论】:
-
sender.tabButtonBorderWidth = 4.0所以你改变了按钮底栏。但是您不要将另一个更改为 0。另外,强烈建议:以小写开头命名您的 var。 -
@Larme 我确实改变了另一个。我更改了 PhoneButton 上的 EmailButton 边框,反之亦然。
-
@EgaSetyaPutra 只需用我在下面回答的按钮更改您的 Button 类。你不会遇到这个问题。