有没有解决这个问题以及如何在UITextField中放置图标? 这是我的代码。
func roundCorners(corners:UIRectCorner, radius:CGFloat) {
let bounds = self.bounds
let maskPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let maskLayer = CAShapeLayer()
maskLayer.frame = bounds
maskLayer.path = maskPath.cgPath
self.layer.mask = maskLayer
let frameLayer = CAShapeLayer()
frameLayer.frame = bounds
frameLayer.path = maskPath.cgPath
frameLayer.strokeColor = UIColor.darkGray.cgColor
frameLayer.fillColor = UIColor.init(red: 247, green: 247, blue: 247, alpha: 0).cgColor
self.layer.addSublayer(frameLayer)
}
func roundTopCornersRadius(radius:CGFloat) {
self.roundCorners(corners: [UIRectCorner.topLeft, UIRectCorner.topRight], radius:radius)
}
func roundBottomCornersRadius(radius:CGFloat) {
self.roundCorners(corners: [UIRectCorner.bottomLeft, UIRectCorner.bottomRight], radius:radius)
}
在viewDidLoad()
中username.roundTopCornersRadius(radius: 8)
password.roundBottomCornersRadius(radius: 8)
这就是我所拥有的
我希望我的textField看起来像这样
答案 0 :(得分:1)
要添加图像,请使用UITextField的leftView属性。
您的边框代码似乎很好,但请记住在添加cornerRadius之前确保文本字段的布局已完成。您可以调用view.layoutIfNeeded()以确保已调用它。或者(更好的解决方案),您可以覆盖自定义文本字段中的layoutSubviews()
,并确保在文本字段的布局更改时更改图层的边界。
将textField的borderStyle设置为.none。
@IBDesignable
class CustomTextField: UITextField {
@IBInspectable
var image: UIImage? {
didSet {
imageView.image = image
}
}
var imageView: UIImageView = UIImageView()
override func awakeFromNib() {
super.awakeFromNib()
self.borderStyle = .none
setupImageView()
}
func roundCorners(corners:UIRectCorner, radius:CGFloat) {
let bounds = self.bounds
let maskPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let maskLayer = CAShapeLayer()
maskLayer.frame = bounds
maskLayer.path = maskPath.cgPath
self.layer.mask = maskLayer
let frameLayer = CAShapeLayer()
frameLayer.frame = bounds
frameLayer.path = maskPath.cgPath
frameLayer.strokeColor = UIColor.darkGray.cgColor
frameLayer.fillColor = UIColor.init(red: 247, green: 247, blue: 247, alpha: 0).cgColor
self.layer.addSublayer(frameLayer)
}
func setupImageView() {
imageView = UIImageView(frame: CGRect(x:5,y:0,width:35,height:25))
imageView.image = image
imageView.contentMode = .scaleAspectFit
self.leftView = imageView
self.leftViewMode = .always
}
func roundTopCornersRadius(radius:CGFloat) {
roundCorners(corners: [UIRectCorner.topLeft, UIRectCorner.topRight], radius:radius)
}
func roundBottomCornersRadius(radius:CGFloat) {
roundCorners(corners: [UIRectCorner.bottomLeft, UIRectCorner.bottomRight], radius:radius)
}
}
答案 1 :(得分:0)
您需要实施IBDesignable View
答案 2 :(得分:0)
嗯这真的是自定义的,不确定你是否可以在没有工作的情况下使用原生文本字段。
为什么不这样做呢:
UIView将包含您的两个图标和旁边的两个文本字段:
只需确保不为文本字段设置边框样式:
然后将包含所有内容的UIView的角半径设置为您想要的任何内容;)轻松交配!