如何解决iOS:如何防止UITextField离开屏幕
我目前正在开发一个应用程序,该应用程序在Vertical StackView内有两个UILabel,在Vertical StackView内有两个UITextField,并且在一个Horizontal StackView内都具有这两个Vertical StackViews:
我有约束条件。当该应用程序在较大的设备(例如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”的类。
此外,在处理UITextField的Controller上的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函数。
谢谢!
解决方法
简单的两步式解决方案:
-
重写
styleTextField
,以便在创建新下划线层之前保留对下划线层的引用,并删除(如果已存在)下划线层。 -
将呼叫移至
styleTextField()
到layoutSubviews
。 (不要忘了打电话给super
。)
选择“更多信息:”标签,并将水平压缩电阻优先级设置为1000
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。