-1

我在 Xcode 9、iOS 11 中使用此代码。

var boolName: Bool = false

override func viewDidLoad() {
    super.viewDidLoad()

}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)

    if boolName == true {
        self.designTextField()
        self.view.layoutIfNeeded()
    }
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    if boolName == false {

        self.designTextField()
        boolName = true
    }
    self.view.layoutIfNeeded()
}

func designTextField() {
    //Set the horizontal line in bottom of text field
    nameLayer.frame = CGRect(x: 0, y: self.tfName.bounds.size.height, width: self.tfName.bounds.size.width, height: 1)
    nameLayer.backgroundColor = UIColor.lightGray.cgColor
    tfName.layer.addSublayer(nameLayer)

    //Set the horizontal line in bottom of text field
    phoneLayer.frame = CGRect(x: 0, y: self.tfPhone.bounds.size.height, width: self.tfPhone.bounds.size.width, height: 1)
    phoneLayer.backgroundColor = UIColor.lightGray.cgColor
    tfPhone.layer.addSublayer(phoneLayer)

    //Set the horizontal line in bottom of text field
    emailLayer.frame = CGRect(x: 0, y: self.tfEmail.bounds.size.height, width: self.tfEmail.bounds.size.width, height: 1)
    emailLayer.backgroundColor = UIColor.lightGray.cgColor
    tfEmail.layer.addSublayer(emailLayer)
}

在 iPad 中使用该代码和测试时。问题是当我在横向模式下旋转 iPad 时,文本字段的水平线(底部)发生冲突。

纵向模式下的 iPad

横向模式下的 iPad

有人可以帮忙吗?

4

1 回答 1

0

案例if boolName == false在横向模式下停止重绘,将其删除。在方法 designTextField 中,设置线层的名称,然后您就可以获取和更新它们。

let kLineName = "nameLine"

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    self.designTextField()
}

func designTextField()
{
    //Set the horizontal line in bottom of text field
    if let index = tfName.layer.sublayers?.index(where: { (layer) -> Bool in
        return layer.name == kLineName
    }) {
        //Update line's frame if it's existed.
        let nameLayer = tfName.layer.sublayers![index]
        nameLayer.frame = CGRect(x: 0, y: self.tfName.bounds.size.height, width: self.tfName.bounds.size.width, height: 1)
    }
    else{
        //Add layer if it's not existed.
        nameLayer.frame = CGRect(x: 0, y: self.tfName.bounds.size.height, width: self.tfName.bounds.size.width, height: 1)
        nameLayer.backgroundColor = UIColor.lightGray.cgColor
        nameLayer.name = kLineName
        tfName.layer.addSublayer(nameLayer)
    }

    //Same to the phoneLayer and emailLayer ......

}
于 2018-02-24T06:13:51.047 回答