Skip to content

Instantly share code, notes, and snippets.

@codetalks-new
Last active August 29, 2015 14:22
Show Gist options
  • Select an option

  • Save codetalks-new/d31c7a41f29e7ddca728 to your computer and use it in GitHub Desktop.

Select an option

Save codetalks-new/d31c7a41f29e7ddca728 to your computer and use it in GitHub Desktop.
TextField 前面带一个 Icon 的Custom View 实现
//
// IconTextField.swift
// ExamTimePickerDemo
//
// Created by Haizhen Lee on 15/5/29.
// Copyright (c) 2015年 banxi1988. All rights reserved.
// 以下用到的一些 AutoLayout的自定义封装方法见
// https://gist.github.com/banxi1988/8b07212cadaddd28384f
import UIKit
@IBDesignable
class IconTextField: UIView {
let iconImageView = UIImageView(frame: CGRectZero)
let textField = UITextField(frame: CGRectZero)
let iconPadding :CGFloat = 15
let padding = UIEdgeInsets(top: 4, left: 15, bottom: 4, right: 15)
func commonInit(){
addSubview(iconImageView)
addSubview(textField)
iconImageView.setTranslatesAutoresizingMaskIntoConstraints(false)
iconImageView.pinCenterY()
iconImageView.pinLeading(padding:padding.left)
iconImageView.contentMode = UIViewContentMode.ScaleAspectFit
textField.setTranslatesAutoresizingMaskIntoConstraints(false)
textField.setContentHuggingPriority(240, forAxis: UILayoutConstraintAxis.Horizontal)
textField.pinCenterY()
textField.pinLeadingToSibling(iconImageView, withMargin: iconPadding)
textField.pinTrailing(padding:padding.right)
textField.textAlignment = .Left
invalidateIntrinsicContentSize()
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
let bundle = NSBundle(forClass: self.dynamicType)
let image = UIImage(named: "icon_locate", inBundle: bundle, compatibleWithTraitCollection: self.traitCollection)
iconImageView.image = image
textField.text = "大学英语四级"
backgroundColor = UIColor.lightGrayColor()
}
override func intrinsicContentSize() -> CGSize {
let iconSize = iconImageView.intrinsicContentSize()
let textSize = textField.intrinsicContentSize()
let width = padding.left + iconSize.width + iconPadding + textSize.width + padding.right
let height = padding.top + max(iconSize.height, textSize.height) + padding.bottom
return CGSize(width: width, height: height)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment