ios - 自定义 UITextField 中的边框宽度和占位符
问题描述
我想做这个 TextField
所以我写了这门课
class UnderLineTextField:UITextField{
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let border = CALayer()
let width = CGFloat(2.0)
border.borderColor = UIColor.darkgray().cgColor
border.frame = CGRect(x: 0, y: frame.size.height - width, width: frame.size.width, height: frame.size.height)
textColor = UIColor.gold()
backgroundColor = UIColor.clear
border.borderWidth = width
layer.addSublayer(border)
layer.masksToBounds = true
attributedPlaceholder = NSAttributedString(string: "",
attributes: [NSAttributedStringKey.foregroundColor: UIColor.darkgray()])}
}
但是有两个问题
下划线不等于TextField,如果我添加更多的宽度
width: frame.size.width + 500
,问题可以解决,但为什么呢?我应该传递给什么正确的值width:
?attributedPlaceholder
将替换我在 xib 中设置的占位符,如何在不添加空字符串的情况下更改占位符?
解决方案
看来你的代码没问题。
使用以下代码设置占位符:
class UnderLineTextField:UITextField{
@IBInspectable var borderColor: UIColor = UIColor.white {
didSet {
layer.borderColor = borderColor.cgColor
}
}
@IBInspectable var placeHolderText: String = "default place holder" {
didSet {
attributedPlaceholder = NSAttributedString(string: placeHolderText,
attributes: [NSAttributedStringKey.foregroundColor: UIColor.darkGray])}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let border = CALayer()
let width = CGFloat(2.0)
border.borderColor = UIColor.darkGray.cgColor
border.frame = CGRect(x: 0, y: frame.size.height - width, width: frame.size.width, height: frame.size.height)
textColor = UIColor.lightGray
backgroundColor = UIColor.clear
border.borderWidth = width
layer.addSublayer(border)
layer.masksToBounds = true
attributedPlaceholder = NSAttributedString(string: placeHolderText,
attributes: [NSAttributedStringKey.foregroundColor: UIColor.darkGray])}
}
结果将如下所示:
推荐阅读
- node.js - 每次添加孩子时调用的最佳 Firebase 云函数
- javascript - Bootstrap Carousel - 在活动幻灯片上自动播放视频
- javascript - 如何使用 Vue / JavaScript 在移动设备上触发长按(单击并按住)
- python - 在 Python 中填写 CSV 文件中缺失的数据
- flutter - 我无法设计以下 UI
- kubernetes - 检索无法将 yaml 转换为 json 错误 kubernetes yaml
- flutter - 我被困在运行 gradle 任务“assembledebug”
- flutter - Flutter:如何在 Wrap 小部件内滚动列表?
- aspnetzero - 使用 RAD 电动工具添加实体时的样式问题
- android - 如何显示弹出通知,例如什么是应用呼叫通知?