func setUnderlineTo(textFields:UITextField){
let buttonBroder = CALayer()
buttonBroder.frame = CGRectMake(0.0, textFields.frame.height - 1, textFields.frame.size.width, 1.0)
buttonBroder.backgroundColor = UIColor(red: 155.0/255.0, green: 205.0/255.0, blue: 210.0/255.0, alpha: 1.0).CGColor
textFields.layer.addSublayer(buttonBroder)
}
func setUnderlineToButton(button:UIButton){
let buttonBroder = CALayer()
buttonBroder.frame = CGRectMake(0.0, button.frame.height - 1, button.frame.size.width, 1.0)
buttonBroder.backgroundColor = UIColor(red: 155.0/255.0, green: 205.0/255.0, blue: 210.0/255.0, alpha: 1.0).CGColor
button.layer.addSublayer(buttonBroder)
}
调用viewDidLoad
形式的这些方法适用于UITextField
但不适用于UIButton
override func viewDidLoad() {
super.viewDidLoad()
setUnderlineToButton(dateBtn)
setUnderlineTo(timeTxtField)
setUnderlineTo(agendaTxtField)
}
答案 0 :(得分:1)
使用以下代码为我添加下划线。由于您为UIButton
和UITextField
添加了相同的下划线,因此我简化了代码以使用父类UIView
。
override func viewDidLoad() {
super.viewDidLoad()
let dateBtn = UIButton(type: UIButtonType.Custom);
dateBtn.frame = CGRectMake(50, 100, 100, 50);
dateBtn .setTitle("btn", forState: UIControlState.Normal);
dateBtn.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
self.view.addSubview(dateBtn);
let timeTxtField:UITextField = UITextField(frame: CGRectMake(50, 150, 100,50));
self.view.addSubview(timeTxtField);
let agendaTxtField:UITextField = UITextField(frame: CGRectMake(50, 200, 100,50));
self.view.addSubview(agendaTxtField)
setUnderline(dateBtn)
setUnderline(timeTxtField)
setUnderline(agendaTxtField)
}
func setUnderline(view:UIView){
let underline = CALayer();
underline.frame = CGRectMake(0, view.frame.height - 1, view.frame.size.width, 1)
underline.backgroundColor = UIColor(red: 155.0/255.0, green: 205.0/255.0, blue: 210.0/255.0, alpha: 1.0).CGColor
view.layer.addSublayer(underline)
}