gpt4 book ai didi

iOS - @IBDesignable UITextField 子类在 IB 中正确显示,但在设备上不正确

转载 作者:行者123 更新时间:2023-11-28 08:42:28 26 4
gpt4 key购买 nike

我有一个自定义的 UITextField 子类,它有一个 @IBInspectable 属性来圆化文本字段的顶角或底角。在 Interface Builder 中一切正常,四舍五入正确的角落等等,但是当我在 device 上运行应用程序时(或在模拟器中),它忽略我的自定义类,只显示默认的 UITextField 实现(我在 IB 中将 borderStyle 设置为 none)。

这是我的自定义类:

@IBDesignable
class RoundedCornersTextField: UITextField {

@IBInspectable var roundBottom: Bool = false
@IBInspectable var cornerRadius: CGFloat = 22

override func textRectForBounds(bounds: CGRect) -> CGRect {
return CGRectInset(bounds, 22, 0)
}

override func editingRectForBounds(bounds: CGRect) -> CGRect {
return CGRectInset(bounds, 22, 0)
}

override func drawRect(rect: CGRect) {
super.drawRect(rect)

let cornerRadii: CGSize = CGSize(width: cornerRadius, height: cornerRadius)

let topBounds = CGRect(x: 0, y: 0, width: rect.width, height: rect.height / 2)
let bottomBounds = CGRect(x: 0, y: rect.height / 2, width: rect.width, height: rect.height / 2)

let topPathRoundedCorners: UIRectCorner = roundBottom ? [] : [.TopLeft, .TopRight]
let bottomPathRoundedCorners: UIRectCorner = roundBottom ? [.BottomLeft, .BottomRight] : []

let topPath = UIBezierPath(roundedRect: topBounds, byRoundingCorners: topPathRoundedCorners, cornerRadii: cornerRadii)
let bottomPath = UIBezierPath(roundedRect: bottomBounds, byRoundingCorners: bottomPathRoundedCorners, cornerRadii: cornerRadii)

topPath.appendPath(bottomPath)

let layer = CAShapeLayer()

layer.path = topPath.CGPath
layer.bounds = rect
layer.position = self.center
layer.fillColor = UIColor.whiteColor().CGColor
layer.lineWidth = 0
layer.strokeColor = UIColor.clearColor().CGColor

self.layer.insertSublayer(layer, atIndex: 0)

}
}

最佳答案

不知道您是否仍在寻找答案我在尝试使用左 View 图标创建自定义文本字段时遇到了同样的问题这段代码完成了我的所有工作。您几乎可以用您的代码替换两个 init 中的所有代码

import UIKit
@IBDesignable
class IconTextField: UITextField {
var imageView:UIImageView?
@IBInspectable var image: UIImage? {
didSet { imageView?.image = image }
}
override init(frame: CGRect) {
super.init(frame: frame)
let rootView = UIView(frame:CGRect(x:0,y:0,width:45,height:25))
self.imageView = UIImageView(frame:CGRect(x:10,y:0,width:20,height:20))
self.imageView?.tintColor = UIColor.red
self.imageView?.image = image
rootView.addSubview(self.imageView!)
self.leftView = rootView
self.leftViewMode = UITextFieldViewMode.always
}

required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
let rootView = UIView(frame:CGRect(x:0,y:0,width:45,height:25))
self.imageView = UIImageView(frame:CGRect(x:10,y:0,width:20,height:20))
self.imageView?.tintColor = UIColor.red
self.imageView?.image = image
rootView.addSubview(self.imageView!)
self.leftView = rootView
self.leftViewMode = UITextFieldViewMode.always
}



}

关于iOS - @IBDesignable UITextField 子类在 IB 中正确显示,但在设备上不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36128896/

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