gpt4 book ai didi

ios - 如何自定义 UITextField?

转载 作者:可可西里 更新时间:2023-11-01 00:36:11 27 4
gpt4 key购买 nike

我正在关注这个 answer创建自定义 UITextField,但是,我无法获得相同的结果,这是我的做法:

方法一(和原答案一模一样):

extension UITextField {

func useUnderLine() {
let border = CALayer()
let borderWidth = CGFloat(1.0)
border.borderColor = UIColor.white.cgColor
border.frame = CGRect(x: 0, y: self.frame.size.height - borderWidth, width: self.frame.size.width, height: self.frame.size.height)
border.borderWidth = borderWidth
self.layer.addSublayer(border)
self.layer.masksToBounds = true
}
}

override func viewDidLoad() {
super.viewDidLoad()

firstTextField.useUnderLine()
}

方法 2(使用自定义类):

class CustomTextField: UITextField {

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)

let borderWidth = CGFloat(1.0)
self.layer.borderColor = UIColor.white.cgColor
self.layer.frame = CGRect(x: 0, y: self.frame.size.height - borderWidth, width: self.frame.size.width, height: self.frame.size.height)
self.layer.borderWidth = borderWidth
self.backgroundColor = UIColor.black
self.layer.masksToBounds = true
}
}

这两种方法都失败了,但是,我得到了不同的结果:

第一个文本字段使用方法 1,其他 3 个使用方法 2

I want a textfield with only the bottom line, how do I get that?

编辑(这里是 socket 的设置方式):

@IBOutlet weak var firstTextField: UITextField!
@IBOutlet weak var secondTextField: CustomTextField! { didSet { secondTextField.delegate = self } }
@IBOutlet weak var thirdTextField: CustomTextField! { didSet { thirdTextField.delegate = self } }
@IBOutlet weak var fourthTextField: CustomTextField! { didSet { fourthTextField.delegate = self } }

最佳答案

如果您使用Storyboard 创建您的textField,请使用以下内容:

firstTextField.borderStyle = .none
firstTextField.layoutIfNeeded()

let border = CALayer()
let width = CGFloat(2.0)
border.borderColor = UIColor.darkGray.cgColor

print(firstTextField.frame)
border.frame = CGRect(x: 0, y: firstTextField.frame.size.height - width, width: firstTextField.frame.size.width, height: firstTextField.frame.size.height)
border.borderWidth = width

firstTextField.layer.addSublayer(border)
firstTextField.layer.masksToBounds = true

如果您正在创建 textField 以编程方式,请使用以下内容:

let textField = UITextField(frame: CGRect(x: 0, y: 20, width: 100, height: 20))

let border = CALayer()
let width = CGFloat(2.0)
border.borderColor = UIColor.darkGray.cgColor
border.frame = CGRect(x: 0, y: textField.frame.size.height - width, width: textField.frame.size.width, height: textField.frame.size.height)

border.borderWidth = width
textField.borderStyle = .none
textField.layer.addSublayer(border)
textField.layer.masksToBounds = true

self.view.addSubview(textField)

会给你:
enter image description here

关于ios - 如何自定义 UITextField?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39939557/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com