I have a problem, I added secureTextEntry toggle in my text field, but text is on toggle button.
extension UITextField {
fileprivate func setPasswordToggleImage(_ button: UIButton) {
if(isSecureTextEntry){
button.setImage(UIImage(named: "eye-active"), for: .normal)
}else{
button.setImage(UIImage(named: "eye-inactive"), for: .normal)
}
}
func enablePasswordToggle(){
let button = UIButton(type: .custom)
setPasswordToggleImage(button)
button.frame = CGRect(x: CGFloat(self.frame.size.width - 25), y: CGFloat(5), width: CGFloat(25), height: CGFloat(25))
button.addTarget(self, action: #selector(self.togglePasswordView), for: .touchUpInside)
self.rightView = button
self.rightViewMode = .always
}
#IBAction func togglePasswordView(_ sender: Any) {
self.isSecureTextEntry.toggle()
setPasswordToggleImage(sender as! UIButton)
}
}
Also I have a bug that places my icon in far right, instead of the place I meant and I don't know why but it's 2nd icon
You can use this directly to add image and padding to your UITextField. Can be done from code as well as storyboard
// MARK: - UITextField
extension UITextField {
#IBInspectable var leftPadding: CGFloat {
get {
return leftView?.frame.size.width ?? 0.0
}
set {
let frame = CGRect(x: 0, y: 0, width: newValue, height: bounds.size.height)
leftView = UIView(frame: frame)
leftViewMode = .always
}
}
#IBInspectable var leftImage: UIImage? {
get {
let imgView = leftView?.subviews.first(where: {$0 is UIImageView}) as? UIImageView
return imgView?.image
}
set {
let frame = CGRect(x: 0, y: 0, width: leftPadding, height: bounds.size.height)
leftView = UIView(frame: frame)
let imgView = UIImageView(frame: frame.insetBy(dx: 4, dy: 4))
imgView.contentMode = .scaleAspectFit
leftView?.addSubview(imgView)
imgView.image = newValue
leftViewMode = .always
}
}
#IBInspectable var rightPadding: CGFloat {
get {
return rightView?.frame.size.width ?? 0.0
}
set {
let frame = CGRect(x: 0, y: 0, width: newValue, height: bounds.size.height)
rightView = UIView(frame: frame)
rightViewMode = .always
}
}
#IBInspectable var rightImage: UIImage? {
get {
let imgView = rightView?.subviews.first(where: {$0 is UIImageView}) as? UIImageView
return imgView?.image
}
set {
let frame = CGRect(x: 0, y: 0, width: rightPadding, height: bounds.size.height)
rightView = UIView(frame: frame)
let imgView = UIImageView(frame: frame.insetBy(dx: 4, dy: 4))
imgView.contentMode = .scaleAspectFit
rightView?.addSubview(imgView)
imgView.image = newValue
rightViewMode = .always
}
}
}
Related
So I added a UIImageView to the right of my UITextField, but I need to add a little bit of padding to the right side so that it doesn't anchor all the way to the right. I tried adding a custom frame but that didn't work, so I'm not too sure how to go about getting that padding. Any help would be much appreaciated.
See TextField Example Here
let titleField : UITextField = {
let titleField = UITextField()
titleField.placeholder = "Title"
titleField.textAlignment = .center
titleField.backgroundColor = .white
titleField.addDoneCancelToolbar()
var imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
let image = UIImage(systemName: "exclamationmark.circle")?.withTintColor(.systemRed, renderingMode: .alwaysOriginal)
imageView.image = image
titleField.rightView = imageView
titleField.rightViewMode = .always
// titleField.rightView?.isHidden = true
return titleField
}()
Subclass UITextField and override https://developer.apple.com/documentation/uikit/uitextfield/1619638-rightviewrect.
Just add the extension :
extension UITextField {
func rightImage(_ image: UIImage?, imageWidth: CGFloat, padding: CGFloat) {
let imageView = UIImageView()
imageView.frame = CGRect(x: padding + 2, y: 0, width: imageWidth, height: frame.height)
imageView.contentMode = .scaleAspectFit
imageView.image = image
let containerView = UIView(frame: CGRect(x: 0, y: 0, width: imageWidth + padding , height: frame.height))
containerView.addSubview(imageView)
rightView = containerView
rightViewMode = .always
}
}
To use it :
if let image = UIImage(named: imagename + ".png") {
titlefield.rightImage(image, imageWidth: 30, padding: 5)
}
When I try create UISlider with gradient background programmatically, it is not working correctly (gradient is repeated many times). When I use the code below with storyboard, everything works fine. Am I missing something here? Thank you!
UISlider subclass
class GradientSlider: UISlider {
var thickness: CGFloat = 20 {
didSet {
setup()
}
}
var sliderThumbImage: UIImage? {
didSet {
setup()
}
}
func setup() {
let minTrackStartColor = UIColor.red
let minTrackEndColor = UIColor.yellow
let maxTrackColor = UIColor.green
do {
self.setMinimumTrackImage(try self.gradientImage(
size: self.trackRect(forBounds: self.bounds).size,
colorSet: [minTrackStartColor.cgColor, minTrackEndColor.cgColor]),
for: .normal)
self.setMaximumTrackImage(try self.gradientImage(
size: self.trackRect(forBounds: self.bounds).size,
colorSet: [maxTrackColor.cgColor, maxTrackColor.cgColor]),
for: .normal)
self.setThumbImage(sliderThumbImage, for: .normal)
} catch {
self.minimumTrackTintColor = minTrackStartColor
self.maximumTrackTintColor = maxTrackColor
}
print("SZ \(self.bounds.size)")
}
func gradientImage(size: CGSize, colorSet: [CGColor]) throws -> UIImage? {
let tgl = CAGradientLayer()
tgl.frame = CGRect.init(x:0, y:0, width:size.width, height: size.height)
tgl.cornerRadius = tgl.frame.height / 2
tgl.masksToBounds = false
tgl.colors = colorSet
tgl.startPoint = CGPoint.init(x:0.0, y:0.5)
tgl.endPoint = CGPoint.init(x:1.0, y:0.5)
UIGraphicsBeginImageContextWithOptions(size, tgl.isOpaque, 0.0);
guard let context = UIGraphicsGetCurrentContext() else { return nil }
tgl.render(in: context)
let image =
UIGraphicsGetImageFromCurrentImageContext()?.resizableImage(withCapInsets:
UIEdgeInsets.init(top: 0, left: size.height, bottom: 0, right: size.height))
UIGraphicsEndImageContext()
return image!
}
override func trackRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(
x: bounds.origin.x,
y: bounds.origin.y,
width: bounds.width,
height: thickness
)
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
}
Adding Slider Programmatically
func addSlider() {
var slider = GradientSlider()
slider.frame = CGRect(x: 30, y: 600, width: view.frame.width - 30, height: 20)
slider.isContinuous = true
slider.value = 0.5
slider.addTarget(self, action: #selector(slide(sender:)), for: .valueChanged)
view.addSubview(slider)
}
original answer
I replaced the addSlider code, and it worked for me.
func addSlider() {
let slider = GradientSlider.init(frame: CGRect(x: 30, y: 100, width: view.frame.width - 30, height: 20))
slider.isContinuous = true
slider.value = 0.5
slider.addTarget(self, action: #selector(slide(sender:)), for: .valueChanged)
view.addSubview(slider)
}
I have set up the left icon in UITextField. When I set text, it is over the left icon. I want to set text after the icon in the UITextField. I have used below code.
let imageView = UIImageView(image: UIImage(named: strImgname))
imageView.frame = CGRect(x: 0, y: 0, width: imageView.image!.size.width , height: imageView.image!.size.height)
let paddingView: UIView = UIView.init(frame: CGRect(x: 0, y: 0, width: 50, height: 30))
paddingView.addSubview(imageView)
txtField.leftViewMode = .always
txtField.leftView = paddingView
You can use #IBDesignable to make a designable UITextField with these capabilities and even more and use it through out your project.
DesignableTextField with Delegate methods when icon in UITextField is tapped:
import Foundation
import UIKit
protocol DesignableTextFieldDelegate: UITextFieldDelegate {
func textFieldIconClicked(btn:UIButton)
}
#IBDesignable
class DesignableTextField: UITextField {
//Delegate when image/icon is tapped.
private var myDelegate: DesignableTextFieldDelegate? {
get { return delegate as? DesignableTextFieldDelegate }
}
#objc func buttonClicked(btn: UIButton){
self.myDelegate?.textFieldIconClicked(btn: btn)
}
//Padding images on left
override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
var textRect = super.leftViewRect(forBounds: bounds)
textRect.origin.x += padding
return textRect
}
//Padding images on Right
override func rightViewRect(forBounds bounds: CGRect) -> CGRect {
var textRect = super.rightViewRect(forBounds: bounds)
textRect.origin.x -= padding
return textRect
}
#IBInspectable var padding: CGFloat = 0
#IBInspectable var leadingImage: UIImage? { didSet { updateView() }}
#IBInspectable var color: UIColor = UIColor.lightGray { didSet { updateView() }}
#IBInspectable var imageColor: UIColor = UIColor.init(hex: "3EB2FF") { didSet { updateView() }}
#IBInspectable var rtl: Bool = false { didSet { updateView() }}
func updateView() {
rightViewMode = UITextFieldViewMode.never
rightView = nil
leftViewMode = UITextFieldViewMode.never
leftView = nil
if let image = leadingImage {
let button = UIButton(type: .custom)
button.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
let tintedImage = image.withRenderingMode(.alwaysTemplate)
button.setImage(tintedImage, for: .normal)
button.tintColor = imageColor
button.setTitleColor(UIColor.clear, for: .normal)
button.addTarget(self, action: #selector(buttonClicked(btn:)), for: UIControlEvents.touchDown)
button.isUserInteractionEnabled = true
if rtl {
rightViewMode = UITextFieldViewMode.always
rightView = button
} else {
leftViewMode = UITextFieldViewMode.always
leftView = button
}
}
// Placeholder text color
attributedPlaceholder = NSAttributedString(string: placeholder != nil ? placeholder! : "", attributes:[NSAttributedStringKey.foregroundColor: color])
}
}
Now its Designable in the Storyboard as follows:
NOTE: Rtl when set to Off icon will move to left of UITextField
Conforming the Delegate in desired ViewController.
class MyViewController: UIViewController, DesignableTextFieldDelegate {
#IBOutlet weak var txtFieldSomeSearch: DesignableTextField!
txtFieldSomeSearch.delegate = self // can be done in storyboard as well
... // other codes
func textFieldIconClicked(btn: UIButton) {
print("MyViewController : textFieldIconClicked")
}
... // other codes
}
Finally Output :
Using the extension in Swift4, We can easily put the image on the right or on the left with padding to TextField.
extension UITextField {
//MARK:- Set Image on the right of text fields
func setupRightImage(imageName:String){
let imageView = UIImageView(frame: CGRect(x: 10, y: 10, width: 20, height: 20))
imageView.image = UIImage(named: imageName)
let imageContainerView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 55, height: 40))
imageContainerView.addSubview(imageView)
rightView = imageContainerView
rightViewMode = .always
self.tintColor = .lightGray
}
//MARK:- Set Image on left of text fields
func setupLeftImage(imageName:String){
let imageView = UIImageView(frame: CGRect(x: 10, y: 10, width: 20, height: 20))
imageView.image = UIImage(named: imageName)
let imageContainerView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 55, height: 40))
imageContainerView.addSubview(imageView)
leftView = imageContainerView
leftViewMode = .always
self.tintColor = .lightGray
}
}
Use code as for right image setup:-
self.password_text_field.setupRightImage(imageName: "unlock")
Output :)
please use the below code
//Left side icon
textField.leftViewMode = UITextFieldViewMode.Always
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
let image = UIImage(named: imageName)
imageView.image = image
textField.leftView = imageView
//Right side icon
textField.rightViewMode = UITextFieldViewMode.Always
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
let image = UIImage(named: imageName)
imageView.image = image
textField.rightView = imageView
Extension to UITextField in Swift 5. This allows you to check if the image is a system image, otherwise, you use a custom image. You can also set which side of the text field you want the image on using the TextFieldImageSide enumeration.
enum TextFieldImageSide {
case left
case right
}
extension UITextField {
func setUpImage(imageName: String, on side: TextFieldImageSide) {
let imageView = UIImageView(frame: CGRect(x: 10, y: 5, width: 30, height: 30))
if let imageWithSystemName = UIImage(systemName: imageName) {
imageView.image = imageWithSystemName
} else {
imageView.image = UIImage(named: imageName)
}
let imageContainerView = UIView(frame: CGRect(x: 0, y: 0, width: 45, height: 40))
imageContainerView.addSubview(imageView)
switch side {
case .left:
leftView = imageContainerView
leftViewMode = .always
case .right:
rightView = imageContainerView
rightViewMode = .always
}
}
}
Usage:
searchBar.setUpImage(imageName: "mappin.and.ellipse", on: .left)
Produces the following:
I am trying to put multiple buttons in a scrollView but it just scrolls background view.
class HomeVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Home"
let scrollView = UIScrollView()
let view = UIView()
scrollView.frame = self.view.bounds
self.view.backgroundColor = .green
scrollView.backgroundColor = .blue
scrollView.addSubview(view)
self.view.addSubview(scrollView)
scrollView.isPagingEnabled = true
scrollView.contentSize = CGSize(width: self.view.frame.size.width, height: self.view.frame.size.height * 3)
view.frame = CGRect(x: 0, y: self.view.frame.size.height, width: self.view.frame.size.width, height: self.view.frame.size.height)
view.backgroundColor = .yellow
attractivePlaceButtonSetup()
eatDrinkButtonSetup()
ShoppingButtonSetup()
festivalEventButtonSetup()
hotelGuestHouseButtonSetup()
travellerEssentialButtonSetup()
dealButtonSetup()
seeDoButtonSetup()
}
I wrote this code for button frame
func eatDrinkButtonSetup(){
let button = UIButton()
button.frame = CGRect(x: 5, y: 225, width: self.view.frame.size.width - 10, height: 150)
button.setTitle("Eat & Drink", for: .normal)
button.setBackgroundImage(#imageLiteral(resourceName: "imageName"), for: .normal)
button.titleEdgeInsets = UIEdgeInsets(top: -120, left: -200, bottom: 0, right: 0)
button.addTarget(self, action: #selector(targetEatDrink), for: .touchUpInside)
view.addSubview(button)
}
}
I also try to such way but it just scroll a button.
scrollView.addSubview(attractivePlaceButtonSetup)
self.view.addSubview(scrollView)
//Try this...
//Background Scroll Creation
var stickersScrollViewCount = 0
func stickersScrollContents() {
var xCoord: CGFloat = 5
let yCoord: CGFloat = 5
let buttonWidth:CGFloat = 45.0
let buttonHeight: CGFloat = 45.0
let gapBetweenButtons: CGFloat = 5
for i in 0..<stickersImageArray.count{
stickersScrollViewCount = i
// Button properties
let filterButton = UIButton(type: .custom)
filterButton.frame = CGRect(x: xCoord, y: yCoord, width: buttonWidth, height: buttonHeight)
filterButton.tag = stickersScrollViewCount
filterButton.backgroundColor = UIColor.clear
filterButton.setTitleColor(UIColor.white, for: .normal)
filterButton.titleLabel?.adjustsFontSizeToFitWidth = true
filterButton.showsTouchWhenHighlighted = true
let myimage = UIImage(named: stickersImageArray[stickersScrollViewCount])
filterButton.setImage(myimage, for: .normal)
filterButton.addTarget(self, action:#selector(StickersActionTapped), for: .touchUpInside)
filterButton.layer.cornerRadius = 5
filterButton.clipsToBounds = true
xCoord += buttonWidth + gapBetweenButtons
bgScrollView.addSubview(filterButton)
}
bgScrollView.contentSize = CGSize(width: buttonWidth * CGFloat(stickersScrollViewCount+2), height: yCoord)
}
//Call the function where ever you want viewDidLoad() or on Button Click!!
//Hope this helps!!!
I am currently messing around with IBDesignable Views, and I am curious if anyone has been able to solve this. I would like to have views added through the interface builder be automatically arranged using a custom layout algorithm within my subview. The view works great when I run the app, but in the interface builder, the views do not rearrange in real time.
I have tried debugging my UIView class, but it seems at all times when the interface builder is initializing the element, it thinks it has zero subviews. It seems the interface builder does not give you a chance to arrange these views after the fact. However, I'm wondering if maybe there is just something I'm missing. Is it possible to rearrange subviews added from the interface builder within an IBDesignable class, and have the views show up rearranged in the interface builder?
Try using the provided method for a custom view and IBDesignable if you are not already. You also might need to refresh your views in Xcode or have it automatically refresh views. Below is the function you may be missing. This is never called in a live app. It is only called in Xcode IB.
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setUpView()
}
In this instance setUpView is laying out my subviews.
Here is an example that I made. https://github.com/agibson73/ICONButton
import UIKit
#IBDesignable class AGIconButton: UIControl {
private var iconImageView : UIImageView!
private var iconLabel : UILabel!
private var mainSpacer : UIView!
private var highlightView:UIView!
private var widthContraint : NSLayoutConstraint!
var padding : CGFloat = 5
override init(frame: CGRect) {
super.init(frame: frame)
setUpView()
addTarget(self, action: #selector(AGIconButton.userDidTouchDown), for: .touchDown)
addTarget(self, action: #selector(AGIconButton.userDidTouchUp), for: .touchUpInside)
addTarget(self, action: #selector(AGIconButton.userDidTouchUpOutside), for: .touchUpOutside)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUpView()
addTarget(self, action: #selector(AGIconButton.userDidTouchDown), for: .touchDown)
addTarget(self, action: #selector(AGIconButton.userDidTouchUp), for: .touchUpInside)
addTarget(self, action: #selector(AGIconButton.userDidTouchUpOutside), for: .touchUpOutside)
}
//only called at design time
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setUpView()
addTarget(self, action: #selector(AGIconButton.userDidTouchDown), for: .touchDown)
addTarget(self, action: #selector(AGIconButton.userDidTouchUp), for: .touchUpInside)
addTarget(self, action: #selector(AGIconButton.userDidTouchUpOutside), for: .touchUpOutside)
}
#IBInspectable var iconImage: UIImage = UIImage() {
didSet {
iconImageView.image = iconImage
}
}
#IBInspectable var imageSize: CGFloat = 40 {
didSet {
setUpView()
}
}
#IBInspectable var imagePadding: CGFloat = 10 {
didSet {
setUpView()
}
}
#IBInspectable var iconText: String = "Icon Button Time" {
didSet {
setUpView()
}
}
#IBInspectable var iconTextSize: CGFloat = 15 {
didSet {
setUpView()
}
}
#IBInspectable var iconTextColor: UIColor = UIColor.black {
didSet {
setUpView()
}
}
#IBInspectable var alignment: Int = 1 {
didSet {
setUpView()
}
}
override var intrinsicContentSize: CGSize {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: iconTextSize)
label.text = iconText
label.sizeToFit()
return CGSize(width: imageSize + label.frame.width + imagePadding + (padding * 2), height: CGFloat(max(label.frame.height, imageSize) + padding * 2))
}
#IBInspectable var highLightColor: UIColor = UIColor.lightGray {
didSet {
setUpView()
}
}
#IBInspectable var shouldBounce: Bool = true
#IBInspectable var borderColor: UIColor = UIColor.clear {
didSet {
layer.borderColor = borderColor.cgColor
}
}
#IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
#IBInspectable var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
private func setUpView(){
if iconImageView == nil{
iconImageView = UIImageView(image: iconImage)
iconImageView.contentMode = .scaleAspectFit
iconImageView.isUserInteractionEnabled = false
self.addSubview(iconImageView)
}
if mainSpacer == nil{
mainSpacer = UIView(frame: CGRect(x: 0, y: 0, width: imagePadding, height: self.bounds.height))
mainSpacer.isUserInteractionEnabled = false
self.addSubview(mainSpacer)
}
if iconLabel == nil{
iconLabel = UILabel()
iconLabel.isUserInteractionEnabled = false
self.addSubview(iconLabel)
}
if highlightView == nil{
highlightView = UIView(frame: self.bounds)
highlightView.autoresizingMask = [.flexibleWidth,.flexibleHeight]
highlightView.alpha = 0
highlightView.isUserInteractionEnabled = false
self.addSubview(highlightView)
self.bringSubview(toFront: highlightView)
}
highlightView.backgroundColor = highLightColor
iconLabel.font = UIFont.systemFont(ofSize: iconTextSize)
iconLabel.text = iconText
iconLabel.textColor = iconTextColor
iconLabel.sizeToFit()
var usedWidth : CGFloat = self.intrinsicContentSize.width
if bounds.width < usedWidth{
usedWidth = bounds.width
}
let maxImageHeight = min(self.bounds.height - padding, imageSize)
//resize iconlabel if we have to
if maxImageHeight + imagePadding + iconLabel.bounds.width + padding * 2 > usedWidth{
iconLabel.frame = CGRect(x: 0, y: 0, width: self.bounds.width - iconImageView.bounds.width - imagePadding - padding * 2, height: iconLabel.bounds.height)
iconLabel.fitFontForSize(minFontSize: 1, maxFontSize: iconTextSize, accuracy: 1.0)
}
let maxWidth = (self.bounds.width - iconLabel.bounds.width - maxImageHeight - imagePadding) / 2
switch alignment {
case 0:
//intrinsic left
iconImageView.frame = CGRect(x:padding, y: self.bounds.midY - maxImageHeight/2,width:maxImageHeight, height: maxImageHeight)
mainSpacer.frame = CGRect(x: maxImageHeight + padding, y: 0, width: imagePadding, height: self.bounds.height)
iconLabel.frame = CGRect(x: maxImageHeight + imagePadding + padding, y: 0, width: iconLabel.frame.width, height: bounds.height)
break
case 1:
//intrinsic center
iconImageView.frame = CGRect(x: maxWidth, y: self.bounds.midY - maxImageHeight/2,width:maxImageHeight, height: maxImageHeight)
mainSpacer.frame = CGRect(x: maxWidth + maxImageHeight, y: 0, width: imagePadding, height: self.bounds.height)
iconLabel.frame = CGRect(x: maxWidth + maxImageHeight + imagePadding, y: 0, width: iconLabel.frame.width, height: self.bounds.height)
break
case 2:
//intrinsic icon right text aligned right
iconLabel.frame = CGRect(x: maxWidth, y: 0, width: iconLabel.frame.width, height: self.bounds.height)
iconLabel.textAlignment = .right
mainSpacer.frame = CGRect(x: iconLabel.frame.width + maxWidth, y: 0, width: imagePadding, height: self.bounds.height)
iconImageView.frame = CGRect(x: iconLabel.frame.width + imagePadding + maxWidth, y: self.bounds.midY - maxImageHeight/2,width:maxImageHeight, height: maxImageHeight)
break
case 3:
//intrinsic center invert icon
iconLabel.frame = CGRect(x:maxWidth, y: 0, width: iconLabel.frame.width, height: self.bounds.height)
mainSpacer.frame = CGRect(x: maxWidth + iconLabel.bounds.width, y: 0, width: imagePadding, height: self.bounds.height)
iconImageView.frame = CGRect(x: maxWidth + iconLabel.bounds.width + imagePadding, y: self.bounds.midY - maxImageHeight/2,width:maxImageHeight, height: maxImageHeight)
break
default:
//intrinsic center
iconImageView.frame = CGRect(x: maxWidth, y: self.bounds.midY - maxImageHeight/2,width:maxImageHeight, height: maxImageHeight)
mainSpacer.frame = CGRect(x: maxWidth + maxImageHeight, y: 0, width: imagePadding, height: self.bounds.height)
iconLabel.frame = CGRect(x: maxWidth + maxImageHeight + imagePadding, y: 0, width: iconLabel.frame.width, height: self.bounds.height)
}
}
//layout subviews
override func layoutSubviews() {
super.layoutSubviews()
setUpView()
}
//MARK: Touch Events
//TODO: run on timer to simulate a real press
func userDidTouchDown(){
if shouldBounce == true{
animateBouncyDown()
}else{
self.animateHighlightTo(alpha: 0.3)
}
}
func userDidTouchUp(){
if shouldBounce == true{
animateBouncyUp()
}else{
self.animateHighlightTo(alpha: 0)
}
}
func userDidTouchUpOutside(){
if shouldBounce == true{
animateBouncyUp()
}else{
self.animateHighlightTo(alpha: 0)
}
}
func animateHighlightTo(alpha:CGFloat){
UIView.animate(withDuration: 0.2, animations: { [weak self] in
self?.highlightView.alpha = alpha
})
}
func animateBouncyDown(){
self.transform = CGAffineTransform.identity
UIView.animate(withDuration: 0.15, animations: { [weak self] in
self?.transform = CGAffineTransform(scaleX: 0.85, y: 0.85)
})
}
func animateBouncyUp(){
UIView.animate(withDuration: 0.2, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.8, options: .curveEaseInOut, animations: {[weak self] in
if self != nil{
self?.transform = CGAffineTransform.identity
}
}, completion: nil)
}
}
extension UILabel {
func fitFontForSize( minFontSize : CGFloat = 1.0, maxFontSize : CGFloat = 300.0, accuracy : CGFloat = 1.0) {
var maxFontSize = maxFontSize
var minFontSize = minFontSize
assert(maxFontSize > minFontSize)
layoutIfNeeded() // Can be removed at your own discretion
let constrainedSize = bounds.size
while maxFontSize - minFontSize > accuracy {
let midFontSize : CGFloat = ((minFontSize + maxFontSize) / 2)
font = font.withSize(midFontSize)
sizeToFit()
let checkSize : CGSize = bounds.size
if checkSize.height < constrainedSize.height && checkSize.width < constrainedSize.width {
minFontSize = midFontSize
} else {
maxFontSize = midFontSize
}
}
font = font.withSize(minFontSize)
sizeToFit()
layoutIfNeeded()
}
}
There doesn't seem to be any way to do this. If you drop a custom control into another xib and add subviews to the custom control in Interface Builder, those subviews appear at the same level as the custom control in the view hierarchy when you load the xib. It looks like custom controls can not act as containers in other xibs.