gpt4 book ai didi

iOS 添加 CAShapeLayer 未在运行时显示

转载 作者:行者123 更新时间:2023-11-28 15:25:52 25 4
gpt4 key购买 nike

我有一个文本字段,从 Storyboard添加,尝试使用 CAShapeLayer 和 BeizerPath 在文本字段底部添加行

extension UITextField {

func getLine() {
let x1 = self.frame.origin.x
let y = self.frame.origin.y + self.frame.size.height
let start = CGPoint(x: x1, y: y)

let x2 = self.frame.origin.x + self.frame.size.width
let end = CGPoint(x: x2, y: y)

print("\(start) \(end)")

let path = UIBezierPath()
path.move(to: start)
path.addLine(to: end)

let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.strokeColor = UIColor.black.cgColor
shapeLayer.lineWidth = 1.0
shapeLayer.fillColor = UIColor.clear.cgColor
self.layer.addSublayer(shapeLayer)
}
}

用法:txtFiled.getLine()

但它没有显示。让我知道遗漏了什么或做错了什么?

最佳答案

问题出在您对贝塞尔曲线路径的坐标计算中。您正在使用文本字段框架的原点作为您的路径。当您将路径添加到 UITextField 而不是容器时,您应该使用边界原点来计算路径的坐标。更正以下代码:

extension UITextField {

func getLine() {
let x1 = self.bounds.origin.x
let y = self.bounds.origin.y + self.frame.size.height
let start = CGPoint(x: x1, y: y)

let x2 = self.bounds.origin.x + self.frame.size.width
let end = CGPoint(x: x2, y: y)

print("\(start) \(end)")

let path = UIBezierPath()
path.move(to: start)
path.addLine(to: end)

let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.strokeColor = UIColor.black.cgColor
shapeLayer.lineWidth = 5.0
shapeLayer.fillColor = UIColor.clear.cgColor
self.layer.addSublayer(shapeLayer)
}
}

结帐apple's doc on view programming guide

关于iOS 添加 CAShapeLayer 未在运行时显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45257750/

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