【发布时间】:2020-12-11 08:24:13
【问题描述】:
我目前正在开发一个应用程序,它在 Vertical StackView 中有两个 UILabel,在 Vertical StackView 中有两个 UITextField,在一个 Horizontal StackView 中有这两个垂直 StackView:
我设置了约束。当应用程序在更大的设备(例如 iPhone 11)上运行时,它看起来很完美,您可以在此处看到:
但如果我换成 iPhone 8 等较小的设备,您会看到线条紧贴手机边缘:
我为 TextField 制作下划线的方法是使用我创建的名为 StyledTextField 的类。它看起来像这样:
class StyledTextField: UITextField {
var bottomLine = CALayer()
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
styleTextField()
}
private func styleTextField() {
font = UIFont(name: "Quicksand", size: UIFont.labelFontSize)
// Create the bottom line
bottomLine.frame = CGRect(x: 0, y: frame.height - 2, width: frame.width, height: 2)
bottomLine.backgroundColor = Environment.Colours.primary.cgColor
// Remove border on text field
borderStyle = .none
// Add the line to the text field
layer.addSublayer(bottomLine)
}
func makeUnderlineLight() {
bottomLine.backgroundColor = Environment.Colours.primaryAssisted.cgColor
}
}
在情节提要中,我将 UITextField 类指定为“StyledTextField”的类。
此外,在控制器上处理 UITextFields 的 viewDidLoad 函数中,我调用了 setUpUI() 函数,该函数执行以下操作:
func setUpUI() {
title = "Add Task"
taskNameTextField.attributedPlaceholder = NSAttributedString(string: "Name", attributes: [NSAttributedString.Key.foregroundColor: Environment.Colours.lightGray])
moreInfoTextField.attributedPlaceholder = NSAttributedString(string: "(Optional)", attributes: [NSAttributedString.Key.foregroundColor: Environment.Colours.lightGray])
setUpDatePicker()
moreInfoTextField.makeUnderlineLight()
if isEditing() {
showTaskToEdit()
}
view.backgroundColor = Environment.Colours.secondary
}
如您所见,我在其中调用了makeUnderlineLight() StyledTextField 函数。
谢谢!
【问题讨论】:
-
“我确定这个问题与我如何创建下划线无关。”任何时候你确定,你都可能错了。所以在这种情况下。我敢打赌,这正是问题所在。
-
了解文本字段是否真的离开屏幕的方法是使用 View Debugger。试试看。
-
@matt 好的,很公平。如果您有兴趣,我添加了用于创建下划线的代码。
-
不,你没有。一切都取决于您何时调用该方法,而这正是您继续隐藏的内容。 ——你看,我怀疑你说的太早了。这取决于文本字段的
frame。但是如果你在自动布局运行之前调用它,你会得到wrong frame,这正是你所抱怨的。您需要将此方法与调整文本字段的大小协调,无论这种情况如何以及何时发生。 -
您的方法也有问题,因为如果多次调用它,您将获得多个下划线层。但它需要多次调用,因为文本字段可以调整大小。
标签: ios swift autolayout storyboard uitextfield