在UIButton中添加CAlayer无法正常工作

时间:2016-07-09 15:09:38

标签: swift

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)
}

enter image description here 日期基础是按钮,时间和议程基础是UIButton

1 个答案:

答案 0 :(得分:1)

使用以下代码为我添加下划线。由于您为UIButtonUITextField添加了相同的下划线,因此我简化了代码以使用父类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)
}

enter image description here