iOS 自定义控件
iOS控件创建有两种:
1。 用frame初始化view,然后用addSubview。init(frame:)
2。 用storyboard,然后载入。init?(coder:)
每一个UIView都有init?(coder:)
一、xib的形式
class OneLineTextField: UIView ,UITextFieldDelegate{
//界面变量初始化
override func awakeFromNib() {
self.txtContent.delegate = self
}
@IBOutlet weak var txtContent: UITextField!
@IBOutlet weak var line: UIView!
func textFieldDidEndEditing(_ textField: UITextField) {
ChangeLine()
}
func textFieldDidBeginEditing(_ textField: UITextField) {
ChangeLine()
}
@discardableResult
func ChangeLine() {
if self.txtContent.isFirstResponder
{
self.line.backgroundColor = UIHelper.mainColor
}else
{
self.line.backgroundColor = UIColor.colorWithHex(hexValue: 0xE5E5E5)
}
}
}

代码应用:主要是应用 addSubview
let nibContents = Bundle.main.loadNibNamed("OneLineTextField", owner: nil, options: nil)
let vMobile:OneLineTextField = nibContents!.last as! OneLineTextField
vMobile.frame = CGRect(x: 0, y: 0, width: self.viewForMobile.frame.width, height: self.viewForMobile.frame.height)
vMobile.txtContent.placeholder = "输入您的手机号"
self.viewForMobile.addSubview(vMobile)
二、完全自定义
class YellowGrayButton: UIButton {
@IBInspectable var cornerRadius = 6
{
didSet {
self.layer.cornerRadius = CGFloat(cornerRadius)
}
}
@IBInspectable var IsAllowClick:Bool = false
{
didSet{
self.isEnabled = IsAllowClick
if self.isEnabled
{
self.layer.backgroundColor = UIHelper.mainColor.cgColor
self.backgroundColor = UIHelper.mainColor
}else
{
self.layer.backgroundColor = UIColor.colorWithHex(hexValue: 0xDBDBDB).cgColor
self.backgroundColor = UIColor.colorWithHex(hexValue: 0xDBDBDB)
}
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.cornerRadius = 6
self.clipsToBounds = true
self.IsAllowClick = !self.IsAllowClick
self.setTitleColor(UIColor.white, for: .normal)
self.layer.backgroundColor = UIColor.colorWithHex(hexValue: 0xDBDBDB).cgColor
self.backgroundColor = UIColor.colorWithHex(hexValue: 0xDBDBDB)
}
}
posted on 2016-10-21 18:46 Jackyzhong123 阅读(139) 评论(0) 收藏 举报
浙公网安备 33010602011771号