iOS-UITextField : extend the bottom line for ANY resolution

标签 ios iphone ipad uitextfield

我使用以下命令创建了一个带有底线的 UITextFiled:

let Bottomline CALayer = ()
bottomLine.frame CGRect = (x: 0, y: usernameTextField.frame.height-7, width: usernameTextField.frame.width, height: 1)
bottomLine.backgroundColor = UIColor.black.cgColor
TextField.borderStyle = UITextBorderStyle.none
TextField.layer.addSublayer (Bottomline)

iPhone 6(右)的结果是这样的:

好的。

✄------------------------

The problem is to run the same application on a Pro iPad, because the bottom line does not extend following the UITextField, but is shorter

这是 iPad Pro 上的结果:

enter image description here

我不明白为什么底线不遵循 UITextField。当我调用底线时,我定义为:

bottomLine.frame CGRect = (x: 0, y: usernameTextField.frame.height-7, width: usernameTextField.frame.width, height: 1)

我已指定底部线条的长度必须为:

width: usernameTextField.frame.width

问题是什么?

EDIT 1: The contrains are correct, because the UITextField adapts to all types of resolution

enter image description here

编辑:2 谢谢马特!现在开始工作吧!!!

enter image description here

最佳答案

I do not understand why the bottom line does not follow the UITextField

因为它是一个层。当其 super 图层(文本字段)更改大小时,图层不会自动更改大小。

因此,每次文本字段大小发生变化时,您都需要重新绘制底线。

但目前,您正在 viewDidLoad 中配置“底线”层。因此,您将其基于文本字段当时所具有的frame。但文本字段尚未达到其实际大小。然后它确实改变了大小,同时你的“底线”层就坐在那里——所以现在它的大小是错误的。

一个简单的解决方案是子类化 UITextField 并在每次调用 layoutSubviews 时重新绘制线条:

class MyTextField : UITextField {
    var lineLayer : CALayer?
    override func layoutSubviews() {
        super.layoutSubviews()
        self.lineLayer?.removeFromSuperlayer()
        let bottomLine = CALayer()
        bottomLine.frame = CGRect(x: 0, y: self.bounds.height-7, width: self.bounds.width, height: 1)
        bottomLine.backgroundColor = UIColor.black.cgColor
        self.layer.addSublayer(bottomLine)
        self.lineLayer = bottomLine
    }
}

如果您的文本字段是 MyTextField,它将完全按照您的意愿运行。

关于iOS-UITextField : extend the bottom line for ANY resolution,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42888437/

相关文章:

iphone - 可以在不越狱的情况下将 iPhone/iPad 屏幕镜像到显示器上吗?

iphone - iOS JSON解析器:如果两个键具有相同的名称会怎样?

iphone - NSFetchedResultsController 中的 NSPredicate 抛出 EXC_BAD_ACCESS

ios - 将 CMAttitude 与 CMCalibrateMagneticField 结合使用

iphone - 如何检测UIWebView的缩放比例

objective-c - UIScrollView 边界尚未在 "viewDidLoad"调整大小

objective-c - 在事件触发时停止自定义 UIButton 将 titleLabel 重置为 IB 默认值

ios - 如何在导航 Controller 堆栈中的 VC 中设置后退按钮,但又从其他地方分离出来?

ios - .svg URL 到 UIImage iOS

iphone - 尝试推送详细 View 时,iPhone应用程序崩溃,因为 “index 0 beyond bounds for empty array”