swift 3 content mode - ios

I have a problem with xcode: I created a draw app where you can draw on the pictures, when I open a picture and I click to draw, the image stretches,
the same thing if I change content mode (aspectFit, aspectFill)
I forget something?
how to set up the content mode correctly?
This is my code:
import UIKit
import Photos
class ViewController: UIViewController {
#IBOutlet var imageView: UIImageView!
#IBOutlet var toolIcon: UIButton!
#IBOutlet var tempImage: UIImageView!
var lastPoint = CGPoint.zero
var swiped = false
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var brushWidth:CGFloat = 10.0
var opacity:CGFloat = 1.0
var tool: UIImageView!
var isDrawing = true
var selectedImage: UIImage!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
imageView.contentMode = UIViewContentMode.scaleAspectFill
tempImage.contentMode = UIViewContentMode.scaleAspectFill
tool = UIImageView()
tool.frame = CGRect(x:self.view.bounds.size.width, y: self.view.bounds.size.height, width: 38, height: 38)
//tool.image = #imageLiteral(resourceName: "Pen")
self.view.addSubview(tool)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?){
swiped = false
if let touch = touches.first {
lastPoint = touch.location(in: self.view)
}
}
func drawLines(fromPoint:CGPoint, toPoint:CGPoint){
UIGraphicsBeginImageContext(self.view.frame.size)
tempImage.image?.draw(in: CGRect(x:0, y:0, width: self.view.frame.width,height: self.view.frame.height))
let context = UIGraphicsGetCurrentContext()
context?.move(to:CGPoint(x:fromPoint.x,y:fromPoint.y))
context?.addLine(to: CGPoint(x:toPoint.x, y: toPoint.y))
tool.center = toPoint
context?.setBlendMode(CGBlendMode.normal)
context?.setLineCap(CGLineCap.round)
context?.setLineWidth(brushWidth)
context?.setStrokeColor(UIColor(red: red, green: green, blue: blue, alpha: 1.0).cgColor)
context?.strokePath()
tempImage.image = UIGraphicsGetImageFromCurrentImageContext()
tempImage.alpha = opacity
UIGraphicsEndImageContext()
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?){
swiped = true
if let touch = touches.first {
let currentPoint = touch.location(in: self.view)
drawLines(fromPoint: lastPoint, toPoint: currentPoint)
lastPoint = currentPoint
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if !swiped {
drawLines(fromPoint: lastPoint, toPoint: lastPoint)
}
// Merge tempImageView into mainImageView
UIGraphicsBeginImageContext(imageView.frame.size)
imageView.image?.draw(in: CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height), blendMode: CGBlendMode.normal, alpha: 1.0)
tempImage.image?.draw(in: CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height), blendMode: CGBlendMode.normal, alpha: opacity)
imageView.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
tempImage.image = nil
}
#IBAction func reset(_ sender: Any) {
self.imageView.image = nil
}
#IBAction func colorPicked(_ sender: UIButton) {
if sender.tag == 0 {
(red,green,blue) = (1,0,0)
}else if sender.tag == 1 {
(red,green,blue) = (0,1,0)
}else if sender.tag == 2{
(red,green,blue) = (0,0,1)
}else if sender.tag == 3 {
(red,green,blue) = (1,0,1)
}else if sender.tag == 4{
(red,green,blue) = (1,1,0)
}else if sender.tag == 5 {
(red,green,blue) = (0,1,1)
}else if sender.tag == 6{
(red,green,blue) = (1,1,1)
}else if sender.tag == 7 {
(red,green,blue) = (0,0,0)
}
}
#IBAction func save(_ sender: Any) {
let actionSheet = UIAlertController(title: "Pick your options", message: "", preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "Pick an image", style: .default, handler: { (_) in
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .photoLibrary
imagePicker.allowsEditing = false
imagePicker.delegate = self
self.present(imagePicker, animated: true, completion: nil)
}))
actionSheet.addAction(UIAlertAction(title: "Save your drawing", style: .default, handler: {(_) in
if let image = self.imageView.image {
UIImageWriteToSavedPhotosAlbum(image, nil,nil,nil)
}
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil))
present(actionSheet, animated: true, completion: nil)
}
#IBAction func erase(_ sender: Any) {
if (isDrawing) {
(red,green,blue) = (1,1,1)
tool.image = #imageLiteral(resourceName: "Gomma")
toolIcon.setImage(#imageLiteral(resourceName: "Pen"), for: .normal)
}else {
(red,green,blue) = (0,0,0)
tool.image = nil
toolIcon.setImage(#imageLiteral(resourceName: "Gomma"), for: .normal)
}
isDrawing = !isDrawing
}
#IBAction func setting(_ sender: Any) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
let settingsVc = segue.destination as! SettingViewController
settingsVc.delegate = self
settingsVc.red = red
settingsVc.green = green
settingsVc.blue = blue
settingsVc.brush = brushWidth
settingsVc.opacity = opacity
}
}
extension ViewController:UINavigationControllerDelegate,UIImagePickerControllerDelegate,SettingsVCDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let imagePicked = info[UIImagePickerControllerOriginalImage] as? UIImage {
self.selectedImage = imagePicked
self.imageView.image = selectedImage
self.tempImage.image = selectedImage
dismiss(animated: true, completion: nil)
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
func settingsViewControllerDidFinish(_settingsVc: SettingViewController) {
self.red = _settingsVc.red
self.green = _settingsVc.green
self.blue = _settingsVc.blue
self.brushWidth = _settingsVc.brush
self.opacity = _settingsVc.opacity
}
}

Related

how to make collapsible/expandable views in swift

I created a collapsible/expandable form on android. please see GIF below
https://giphy.com/gifs/zVvcKtgT9QTaa1O29O
I'm trying to create something similar on ios, so far, i've already created the bottom sheet as seen below
Looking at this GIF https://gfycat.com/dismalbronzeblowfish, you'd notice i'm able to expand and collapse the views, but there's a big gap where the view used to be, the expected behavior is that the space collapses also with an animation
Below is the code for the bottom sheet
class BottomSheetViewController: UIViewController {
// holdView can be UIImageView instead
#IBOutlet weak var holdView: UIView!
#IBOutlet weak var left: UIButton!
#IBOutlet weak var right: UIButton!
#IBOutlet weak var pickupView: UIView!
#IBOutlet weak var deliveryView: UIView!
#IBOutlet weak var deliverydetailsView: UIView!
#IBOutlet weak var pickupDetailsVIew: UIControl!
let fullView: CGFloat = 100
var partialView: CGFloat {
return UIScreen.main.bounds.height - 300
}
override func viewDidLoad() {
super.viewDidLoad()
let gesture = UIPanGestureRecognizer.init(target: self, action: #selector(BottomSheetViewController.panGesture))
view.addGestureRecognizer(gesture)
let pickupTapGesture = UITapGestureRecognizer(target: self, action: #selector(pickupButton))
let deliveryTapGesture = UITapGestureRecognizer(target: self, action: #selector(deliveryButton))
pickupView.addGestureRecognizer(pickupTapGesture)
deliveryView.addGestureRecognizer(deliveryTapGesture)
pickupView.setBorder(radius: 5, color: .black)
deliveryView.setBorder(radius: 5, color: .black)
roundViews()
deliverydetailsView.isHidden = true
pickupDetailsVIew.isHidden = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
prepareBackgroundView()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
UIView.animate(withDuration: 0.6, animations: { [weak self] in
let frame = self?.view.frame
let yComponent = self?.partialView
self?.view.frame = CGRect(x: 0, y: yComponent!, width: frame!.width, height: frame!.height)
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func rightButton(_ sender: AnyObject) {
print("clicked")
}
#objc func pickupButton(_ sender: UITapGestureRecognizer) {
print("tap")
if pickupDetailsVIew.isHidden {
expand(pickupDetailsVIew)
collapse(deliverydetailsView)
} else {
collapse(pickupDetailsVIew)
}
}
#objc func deliveryButton(_ sender: UITapGestureRecognizer) {
print("tap")
if deliverydetailsView.isHidden {
expand(deliverydetailsView)
collapse(pickupDetailsVIew)
} else {
collapse(deliverydetailsView)
// if deliveryView.isHidden && pickupDetailsVIew.isHidden {
//
// }
}
}
func expand(_ view: UIView) {
view.isHidden = false
}
func collapse(_ view: UIView) {
view.isHidden = true
}
// #IBAction func close(_ sender: AnyObject) {
// UIView.animate(withDuration: 0.3, animations: {
// let frame = self.view.frame
// self.view.frame = CGRect(x: 0, y: self.partialView, width: frame.width, height: frame.height)
// })
// }
#objc func panGesture(_ recognizer: UIPanGestureRecognizer) {
let translation = recognizer.translation(in: self.view)
let velocity = recognizer.velocity(in: self.view)
let y = self.view.frame.minY
if ( y + translation.y >= fullView) && (y + translation.y <= partialView ) {
self.view.frame = CGRect(x: 0, y: y + translation.y, width: view.frame.width, height: view.frame.height)
recognizer.setTranslation(CGPoint.zero, in: self.view)
}
if recognizer.state == .ended {
var duration = velocity.y < 0 ? Double((y - fullView) / -velocity.y) : Double((partialView - y) / velocity.y )
duration = duration > 1.3 ? 1 : duration
UIView.animate(withDuration: duration, delay: 0.0, options: [.allowUserInteraction], animations: {
if velocity.y >= 0 {
self.view.frame = CGRect(x: 0, y: self.partialView, width: self.view.frame.width, height: self.view.frame.height)
} else {
self.view.frame = CGRect(x: 0, y: self.fullView, width: self.view.frame.width, height: self.view.frame.height)
}
}, completion: nil)
}
}
func roundViews() {
view.layer.cornerRadius = 5
holdView.layer.cornerRadius = 3
// left.layer.cornerRadius = 10
// right.layer.cornerRadius = 10
// left.layer.borderColor = UIColor(red: 0, green: 148/225, blue: 247.0/255.0, alpha: 1).cgColor
// left.layer.borderWidth = 1
view.clipsToBounds = true
}
func prepareBackgroundView(){
// let blurEffect = UIBlurEffect.init(style: .dark)
// let visualEffect = UIVisualEffectView.init(effect: blurEffect)
// let bluredView = UIVisualEffectView.init(effect: blurEffect)
// bluredView.contentView.addSubview(visualEffect)
//
// visualEffect.frame = UIScreen.main.bounds
// bluredView.frame = UIScreen.main.bounds
//
// view.insertSubview(bluredView, at: 0)
}
}
I need some help/pointers in the right direction from anyone who has done this before, or who knows how to do this
Thank you

How to output image without background?

I have a canvasImageView and draw something on it.
And I want to output an image just contain image region.
My output function is func saveBtnPressed(sender: UIButton).
Like following image, I want to output blue line region.
Have any idea to do this?
Thanks.
class CanvasViewController: UIViewController {
let canvasImageView: CanvasImageView = {
let ui = CanvasImageView()
ui.contentMode = .scaleAspectFit
ui.layer.backgroundColor = UIColor.clear.cgColor
ui.backgroundColor = UIColor.clear
ui.clipsToBounds = true
ui.isMultipleTouchEnabled = false
ui.isUserInteractionEnabled = true
return ui
}()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Color Yourself"
let save = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(saveBtnPressed(sender:)))
let redo = UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(clearBtnPressed(sender:)))
let back = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(cancelBtnPressed(sender:)))
self.navigationItem.rightBarButtonItems = [save, redo]
self.navigationItem.leftBarButtonItem = back
self.setupView()
}
fileprivate func setupView() {
self.view.addSubview(canvasImageView)
if #available(iOS 11.0, *) {
self.canvasImageView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
} else {
self.canvasImageView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: 0).isActive = true
}
self.canvasImageView.snp.makeConstraints { (make) in
make.bottom.left.right.equalToSuperview()
}
}
//MARK: BUTTON ACTION
#objc func cancelBtnPressed(sender: UIBarButtonItem) {
self.dismiss(animated: false, completion: nil)
}
#objc func clearBtnPressed(sender: UIButton) {
canvasImageView.clearCanvas()
}
#objc func saveBtnPressed(sender: UIButton) {
//Here is output image.
UIGraphicsBeginImageContextWithOptions(self.canvasImageView.layer.bounds.size, true, 0.0)
self.canvasImageView.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if let img = image {
UIImageWriteToSavedPhotosAlbum(img, self,#selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}
}
}
class CanvasImageView: UIImageView {
var lineColor = UIColor.red
var lineWidth: CGFloat = 10
var path: UIBezierPath?
var touchPoint: CGPoint!
var startingPoint: CGPoint!
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.startingPoint = touches.first?.location(in: self)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
self.touchPoint = touches.first?.location(in: self)
self.path = UIBezierPath()
path?.move(to: startingPoint)
path?.addLine(to: touchPoint)
self.startingPoint = touchPoint
self.draw()
}
func draw() {
let shapeLayer = CAShapeLayer()
shapeLayer.path = path?.cgPath
shapeLayer.strokeColor = lineColor.cgColor
shapeLayer.lineWidth = lineWidth
shapeLayer.fillColor = UIColor.clear.cgColor
self.layer.addSublayer(shapeLayer)
self.setNeedsDisplay()
}
func clearCanvas() {
guard let drawPath = path else { return }
drawPath.removeAllPoints()
self.layer.sublayers = nil
self.setNeedsDisplay()
}
}

UITabbar Image Not Updating

i want to update image of uitabbar programmatically but it's not updating when i update the image
looks duplicate ???
here is the answer i already tried but no success
UITabBarItem does not update image
UITabBar not showing selected item images in ios 7
how to programmatically change the tabbarItem's image
https://www.appcoda.com/ios-programming-how-to-customize-tab-bar-background-appearance/
Changing tab bar item image and text color iOS
okay now here is my code for customTabbar
// CustomTabBarViewController.swift
// CustomTabBar
import UIKit
class CustomTabBarViewController: UITabBarController, CustomTabBarDataSource, CustomTabBarDelegate, UITabBarControllerDelegate , UISearchBarDelegate, UISearchDisplayDelegate {
var searchController: UISearchController!
let searchBar = UISearchBar()
var btnBarBadge : MJBadgeBarButton!
var btnBar : MJBadgeBarButton!
// #IBOutlet weak var menuButton: UIBarButtonItem!
// MARK: Properties
var meals = [CatModel]()
func onBagdeButtonClick() {
print("button Clicked \(self.btnBarBadge.badgeValue)")
}
func onBarCodeButtonClick() {
self.title = Localization("Categories")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let subContentsVC = storyboard.instantiateViewController(withIdentifier: "Stores") as! Stores
self.navigationController?.pushViewController(subContentsVC, animated: true)
}
func buttonClicked(_ sender: AnyObject?) {
var countt = Int(Constants.cartCount)
if(countt == nil){
countt = 0
}
if(countt!<1){
let alert = UIAlertController(title: Localization("Warning"), message:Localization("YourCartisEmpty"), preferredStyle: .alert)
alert.addAction(UIAlertAction(title: Localization("Ok"), style: .default) { _ in })
self.present(alert, animated: true){}
}else{
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let subContentsVC = storyboard.instantiateViewController(withIdentifier: "Cart") as! Cart
self.navigationController?.pushViewController(subContentsVC, animated: true)
}
}
func searchBarSearchButtonClicked( _ searchBar: UISearchBar)
{
print(searchBar.text ?? "this is value")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let subContentsVC = storyboard.instantiateViewController(withIdentifier: "SearchProduct") as! SearchProduct
subContentsVC.stringPassed = searchBar.text!
self.navigationController?.pushViewController(subContentsVC, animated: true)
}
func actOnSpecialNotificationon() {
searchBar.placeholder = Localization("Search")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.tabBar.isHidden = true
self.selectedIndex = 1
self.delegate = self
searchBar.sizeToFit()
searchBar.delegate = self
self.title = Localization("Categories")
searchBar.placeholder = Localization("Search")
searchBar.tintColor = .black
navigationItem.titleView = searchBar
NotificationCenter.default.addObserver(self, selector: #selector(CustomTabBarViewController.actOnSpecialNotificationon), name: NSNotification.Name(rawValue: mySpecialNotificationKey), object: nil)
let customTabBar = CustomTabBar(frame: self.tabBar.frame)
customTabBar.datasource = self
customTabBar.delegate = self
customTabBar.setup()
self.view.addSubview(customTabBar)
let customButton = UIButton(type: UIButtonType.custom)
customButton.frame = CGRect(x: 0, y: 0, width: 5.0, height: 35.0)
customButton.addTarget(self, action: #selector(self.onBagdeButtonClick), for: .touchUpInside)
customButton.setImage(UIImage(named: "Cart"), for: .normal)
let barcodeButton = UIButton(type: UIButtonType.custom)
barcodeButton.frame = CGRect(x: 0, y: 0, width: 35.0, height: 35.0)
barcodeButton.addTarget(self, action: #selector(self.onBarCodeButtonClick), for: .touchUpInside)
barcodeButton.setImage(UIImage(named: "edit_location"), for: .normal)
self.btnBarBadge = MJBadgeBarButton()
self.btnBar = MJBadgeBarButton()
self.btnBarBadge.setup(customButton: customButton)
self.btnBarBadge.removeBadge()
self.btnBar.setup(customButton: barcodeButton)
self.btnBar.removeBadge()
self.btnBarBadge.badgeValue = "0"
self.btnBarBadge.badgeOriginX = 2.0
self.btnBarBadge.badgeOriginY = -4
self.navigationItem.rightBarButtonItem = self.btnBarBadge
self.navigationItem.rightBarButtonItems = [self.btnBarBadge,self.btnBar]
customButton.addTarget(self, action: #selector(CustomTabBarViewController.buttonClicked(_:)), for: .touchUpInside)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.setNavigationBarItem()
self.btnBarBadge.badgeValue = Constants.cartCount
}
// MARK: - CustomTabBarDataSource
func tabBarItemsInCustomTabBar(_ tabBarView: CustomTabBar) -> [UITabBarItem] {
return tabBar.items!
}
// MARK: - CustomTabBarDelegate
func didSelectViewController(_ tabBarView: CustomTabBar, atIndex index: Int) {
if(index == 0){
self.openLeftMenu()
}else{
self.selectedIndex = index
}
for loop in 0..<(self.tabBar.items?.count)!{
let barbutton = self.tabBar.items![loop]
if(index == loop){
barbutton.image = self.updateImageColor(origImage: barbutton.image!, color: .green)
}else{
barbutton.image = self.updateImageColor(origImage: barbutton.image!, color: .lightGray)
}
}
}
func updateImageColor(origImage:UIImage,color:UIColor)->UIImage{
let tintedImage = origImage.withRenderingMode(.alwaysOriginal)
let imageview = UIImageView(image: tintedImage)
imageview.tintColor = color
return imageview.image!
}
// MARK: - UITabBarControllerDelegate
func tabBarController(_ tabBarController: UITabBarController, animationControllerForTransitionFrom fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return CustomTabAnimatedTransitioning()
}
}
here is the code for CustomTabBar.swift
//
// CustomTabBar.swift
// CustomTabBar
//
import UIKit
protocol CustomTabBarDataSource {
func tabBarItemsInCustomTabBar(_ tabBarView: CustomTabBar) -> [UITabBarItem]
}
protocol CustomTabBarDelegate {
func didSelectViewController(_ tabBarView: CustomTabBar, atIndex index: Int)
}
class CustomTabBar: UIView {
var datasource: CustomTabBarDataSource!
var delegate: CustomTabBarDelegate!
var tabBarItems: [UITabBarItem]!
var customTabBarItems: [CustomTabBarItem]!
var tabBarButtons: [UIButton]!
var initialTabBarItemIndex: Int!
var selectedTabBarItemIndex: Int!
var slideMaskDelay: Double!
var slideAnimationDuration: Double!
var tabBarItemWidth: CGFloat!
var leftMask: UIView!
var rightMask: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.white
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup() {
// get tab bar items from default tab bar
tabBarItems = datasource.tabBarItemsInCustomTabBar(self)
customTabBarItems = []
tabBarButtons = []
initialTabBarItemIndex = 1
selectedTabBarItemIndex = initialTabBarItemIndex
slideAnimationDuration = 0.6
slideMaskDelay = slideAnimationDuration / 2
let containers = createTabBarItemContainers()
createTabBarItemSelectionOverlay(containers)
createTabBarItemSelectionOverlayMask(containers)
createTabBarItems(containers)
}
func createTabBarItemSelectionOverlay(_ containers: [CGRect]) {
let activeColor = UIColor(red: 109/255, green: 187/255, blue: 16/255, alpha: 1.0)
let overlayColors = [activeColor, activeColor, activeColor, activeColor,activeColor]
for index in 0..<tabBarItems.count {
let container = containers[index]
let view = UIView(frame: container)
let selectedItemOverlay = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height))
selectedItemOverlay.backgroundColor = overlayColors[index] //.clear
view.addSubview(selectedItemOverlay)
tabBarItems[index].selectedImage = updateImageColor(origImage: tabBarItems[index].image!, color: .green)
self.addSubview(view)
}
}
func updateImageColor(origImage:UIImage,color:UIColor)->UIImage{
let tintedImage = origImage.withRenderingMode(.alwaysTemplate)
let imageview = UIImageView(image: tintedImage)
imageview.tintColor = color
return imageview.image!
}
func createTabBarItemSelectionOverlayMask(_ containers: [CGRect]) {
tabBarItemWidth = self.frame.width / CGFloat(tabBarItems.count)
let leftOverlaySlidingMultiplier = CGFloat(initialTabBarItemIndex) * tabBarItemWidth
let rightOverlaySlidingMultiplier = CGFloat(initialTabBarItemIndex + 1) * tabBarItemWidth
leftMask = UIView(frame: CGRect(x: 0, y: 0, width: leftOverlaySlidingMultiplier, height: self.frame.height))
leftMask.backgroundColor = UIColor.white
rightMask = UIView(frame: CGRect(x: rightOverlaySlidingMultiplier, y: 0, width: tabBarItemWidth * CGFloat(tabBarItems.count - 1), height: self.frame.height))
rightMask.backgroundColor = UIColor.white
self.addSubview(leftMask)
self.addSubview(rightMask)
}
func createTabBarItems(_ containers: [CGRect]) {
var index = 0
for item in tabBarItems {
let container = containers[index]
let customTabBarItem = CustomTabBarItem(frame: container)
customTabBarItem.setup(item)
self.addSubview(customTabBarItem)
customTabBarItems.append(customTabBarItem)
let button = UIButton(frame: CGRect(x: 0, y: 0, width: container.width, height: container.height))
button.addTarget(self, action: #selector(CustomTabBar.barItemTapped(_:)), for: UIControlEvents.touchUpInside)
customTabBarItem.addSubview(button)
tabBarButtons.append(button)
index += 1
}
self.customTabBarItems[initialTabBarItemIndex].iconView.tintColor = .green //UIColor.white
}
func createTabBarItemContainers() -> [CGRect] {
var containerArray = [CGRect]()
// create container for each tab bar item
for index in 0..<tabBarItems.count {
let tabBarContainer = createTabBarContainer(index)
containerArray.append(tabBarContainer)
}
return containerArray
}
func createTabBarContainer(_ index: Int) -> CGRect {
let tabBarContainerWidth = self.frame.width / CGFloat(tabBarItems.count)
let tabBarContainerRect = CGRect(x: tabBarContainerWidth * CGFloat(index), y: 0, width: tabBarContainerWidth, height: self.frame.height)
return tabBarContainerRect
}
func animateTabBarSelection(from: Int, to: Int) {
let overlaySlidingMultiplier = CGFloat(to - from) * tabBarItemWidth
let leftMaskDelay: Double
let rightMaskDelay: Double
if overlaySlidingMultiplier > 0 {
leftMaskDelay = slideMaskDelay
rightMaskDelay = 0
}
else {
leftMaskDelay = 0
rightMaskDelay = slideMaskDelay
}
UIView.animate(withDuration: slideAnimationDuration - leftMaskDelay, delay: leftMaskDelay, options: UIViewAnimationOptions(), animations: {
self.leftMask.frame.size.width += overlaySlidingMultiplier
}, completion: nil)
UIView.animate(withDuration: slideAnimationDuration - rightMaskDelay, delay: rightMaskDelay, options: UIViewAnimationOptions(), animations: {
self.rightMask.frame.origin.x += overlaySlidingMultiplier
self.rightMask.frame.size.width += -overlaySlidingMultiplier
self.customTabBarItems[from].iconView.tintColor = UIColor.black
self.customTabBarItems[to].iconView.tintColor = UIColor.white
}, completion: nil)
}
func barItemTapped(_ sender : UIButton) {
let index = tabBarButtons.index(of: sender)!
//tabBarItems[index].selectedImage = nil
//tabBarItems[index].image = nil
// tabBarItems[index].image = UIImage(named: "Home_Tab");
animateTabBarSelection(from: selectedTabBarItemIndex, to: index)
selectedTabBarItemIndex = index
delegate.didSelectViewController(self, atIndex: index)
}
}
when i try changing image nothing happen
tabBarItems[index].image = UIImage(named: "Home_Tab")
tabBarItems[index].image = UIImage(named: "Home_Tab")?.withRenderingMode(.alwaysOriginal)
Same for selected image
it works when i set image in createTabBarItemSelectionOverlay method
i tried removing image and setting it again but no success
also tried to set image with .alwaysOriginal render mode no luck
please help where am i doing wrong ??
Thank you...little help will be appriciated

Fabric digits login with phone number button is not appearing in the relevant UIViewController

Hi I'm new to swift and currently I'm working on a project which was done in swift 2.3 for both iPad and iPhone. I did everything as it is in the documentation but the pink color login with phone number button is not appearing in my screen for some reason. The code is bellow.
import UIKit
import SwiftSpinner
import Crashlytics
import Alamofire
import SwiftyJSON
import DigitsKit
class ViewController: UIViewController, UITextFieldDelegate {
var phoneNum : String?
let movement: CGFloat = 20.0
var phoneHeight: CGFloat = 0.0
var appURLs = AppURLs.sharedInstance
var loadingView: UIView!
var Id: Int!
#IBOutlet weak var username: UITextField!
#IBOutlet weak var activity: UIActivityIndicatorView!
#IBOutlet weak var password: UITextField!
#IBAction func signUpButton(sender: AnyObject) {
let storyboard = switchStoryboards()
let vc = storyboard.instantiateViewControllerWithIdentifier("SignUpViewController")
self.presentViewController(vc, animated: false, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
configureLoadingView()
phoneHeight = self.view.frame.height
UIApplication.sharedApplication().statusBarHidden = true
self.username.delegate = self
self.password.delegate = self
self.slideMenuController()?.removeLeftGestures()
let usernameImageView = UIImageView()
if isIphone() {
usernameImageView.frame = CGRect(x: 0, y: 0, width: 36, height: 20)
} else {
usernameImageView.frame = CGRect(x: 0, y: 0, width: 54, height: 30)
}
usernameImageView.image = UIImage(named: "Username")
view.addSubview(usernameImageView)
username.leftView = usernameImageView
username.leftViewMode = UITextFieldViewMode.Always
let passwordImageView = UIImageView()
if isIphone() {
passwordImageView.frame = CGRect(x: 0, y: 0, width: 36, height: 20)
} else {
passwordImageView.frame = CGRect(x: 0, y: 0, width: 54, height: 30)
}
passwordImageView.image = UIImage(named: "Password")
view.addSubview(passwordImageView)
password.leftView = passwordImageView
password.leftViewMode = UITextFieldViewMode.Always
print("Login view did load loaded")
let authButton = DGTAuthenticateButton(authenticationCompletion: { (session, error) in
if (session != nil) {
// TODO: associate the session userID with your user model
let message = "Phone number: \(session!.phoneNumber)"
let alertController = UIAlertController(title: "You are logged in!", message: message, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: .None))
self.presentViewController(alertController, animated: true, completion: .None)
} else {
NSLog("Authentication error: %#", error!.localizedDescription)
}
})
authButton?.center = self.view.center
self.view.addSubview(authButton!)
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.Portrait
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
}
func configureLoadingView() {
loadingView = UIView(frame: CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height))
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let _ = touches.first {
self.view.endEditing(true)
}
super.touchesBegan(touches, withEvent:event)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if textField.tag == 1 {
textField.superview?.viewWithTag(2)?.becomeFirstResponder()
} else {
textField.resignFirstResponder()
}
return true
}
func textFieldDidBeginEditing(textField: UITextField) {
if phoneHeight < 500.0 {
UIView.animateWithDuration(0.3, animations: {
self.view.frame = CGRectOffset(self.view.frame, 0, -self.movement)
})
}
}
func textFieldDidEndEditing(textField: UITextField) {
if phoneHeight < 500.0 {
UIView.animateWithDuration(0.3, animations: {
self.view.frame = CGRectOffset(self.view.frame, 0, self.movement)
})
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func loginAlerts(messages: String) {
self.activity.stopAnimating()
SwiftSpinner.show("Sign in Failed!", animated: false).addTapHandler({
SwiftSpinner.hide()
}, subtitle: messages)
}
func switchStoryboards() -> UIStoryboard {
switch UIDevice.currentDevice().userInterfaceIdiom {
case .Phone:
// It's an iPhone
return UIStoryboard(name: "Main", bundle: nil)
case .Pad:
return UIStoryboard(name: "StoryboardiPad", bundle: nil)
// It's an iPad
case .Unspecified:
return UIStoryboard(name: "Main", bundle: nil)
// Uh, oh! What could it be?
default:
return UIStoryboard(name: "Main", bundle: nil)
}
}
func isIphone() -> Bool {
switch UIDevice.currentDevice().userInterfaceIdiom {
case .Phone:
// It's an iPhone
return true
case .Pad:
return false
// It's an iPad
case .Unspecified:
return true
// Uh, oh! What could it be?
default:
return true
}
}
}

How to add the text in UIImageView in Swift?

I have some issues for editing UIImageView. User can enter the text in imageview then it processes to save it and after that user can view this image with the text .
How can I do this?
I tried and got the solution for adding the text inside the UIImageview.Below is the coding
import UIKit
class ViewController: UIViewController,UINavigationControllerDelegate, UIImagePickerControllerDelegate,UIGestureRecognizerDelegate{
#IBOutlet var imageViewText: UIImageView!
var dynamicTextViewInsideImageView : UITextView!
var strImageSelected : String!
var picker = UIImagePickerController()
var xValue = CGFloat()
var yValue = CGFloat()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
imageViewText.layer.cornerRadius = 5
imageViewText.layer.borderColor = UIColor.blueColor().CGColor
imageViewText.layer.borderWidth = 1
strImageSelected = ""
}
override func viewWillAppear(animated: Bool)
{
let tapRecognizer = UITapGestureRecognizer(target: self, action: Selector("imageTapped:"))
//Add the recognizer to your view.
imageViewText.userInteractionEnabled = true
tapRecognizer.numberOfTapsRequired = 1
imageViewText.addGestureRecognizer(tapRecognizer)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func actionPickImage(sender: AnyObject)
{
var alert:UIAlertController=UIAlertController(title: "Choose Image", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
var cameraAction = UIAlertAction(title: "Camera", style: UIAlertActionStyle.Default)
{
UIAlertAction in
self.openCamera()
}
var gallaryAction = UIAlertAction(title: "Gallary", style: UIAlertActionStyle.Default)
{
UIAlertAction in
self.openGallary()
}
var cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel)
{
UIAlertAction in
}
// Add the actions
picker.delegate = self
alert.addAction(cameraAction)
alert.addAction(gallaryAction)
alert.addAction(cancelAction)
self.presentViewController(alert, animated: true, completion: nil)
}
func openCamera()
{
if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera))
{
picker.sourceType = UIImagePickerControllerSourceType.Camera
self .presentViewController(picker, animated: true, completion: nil)
}
else
{
let alertWarning = UIAlertView(title:"Warning", message: "You don't have camera", delegate:nil, cancelButtonTitle:"OK", otherButtonTitles:"")
alertWarning.show()
}
}
func openGallary()
{
picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(picker, animated: true, completion: nil)
}
//PickerView Delegate Methods
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject])
{
picker .dismissViewControllerAnimated(true, completion: nil)
imageViewText.image=info[UIImagePickerControllerOriginalImage] as? UIImage
strImageSelected = "ImagePicked"
}
func imagePickerControllerDidCancel(picker: UIImagePickerController)
{
println("picker cancel.")
strImageSelected = ""
}
//On the imageView you can add text(Only after you picked the image from Gallery or Camera)
func imageTapped(gestureRecognizer: UITapGestureRecognizer)
{
if strImageSelected.isEmpty{
println("Do not add the textview inside imageview as you have not picked the image from gallery or camera")
}
else
{
println("you picked the image successfully")
dynamicTextViewInsideImageView = UITextView(frame: CGRectMake(xValue,yValue,200,50))
dynamicTextViewInsideImageView.backgroundColor = UIColor( red: 0.9, green: 0.9, blue:0.9, alpha: 1.0 )
imageViewText.addSubview( dynamicTextViewInsideImageView)
}
}
//TouchEvent for Getting X,Y position once we touch inside the imageview
override func touchesBegan(touches: NSSet, withEvent event: UIEvent)
{
if let touch = touches.anyObject() as? UITouch
{
let location = touch.locationInView(imageViewText) as CGPoint
println("the location.x is - \(location.x)")
println("the location.y is - \(location.y)")
xValue = location.x
yValue = location.y
println("the xValue is - \(xValue)")
println("the yValue is - \(yValue)")
}
}
}
Try the following
func waterMarkedImage(waterMarkText:String, corner:WaterMarkCorner = .BottomRight, margin:CGPoint = CGPoint(x: 20, y: 20), waterMarkTextColor:UIColor = UIColor.whiteColor(), waterMarkTextFont:UIFont = UIFont.systemFontOfSize(20), backgroundColor:UIColor = UIColor.clearColor()) -> UIImage{
let textAttributes = [NSForegroundColorAttributeName:waterMarkTextColor, NSFontAttributeName:waterMarkTextFont]
let textSize = NSString(string: waterMarkText).sizeWithAttributes(textAttributes)
var textFrame = CGRectMake(0, 0, textSize.width, textSize.height)
print(textSize.height)
var imageSize = self.size
imageSize = CGSize(width: imageSize.width, height: (imageSize.height+textSize.height))
switch corner{
case .TopLeft:
textFrame.origin = margin
case .TopRight:
textFrame.origin = CGPoint(x: imageSize.width - textSize.width - margin.x, y: margin.y)
case .BottomLeft:
textFrame.origin = CGPoint(x: margin.x, y: imageSize.height - textSize.height - margin.y)
case .BottomRight:
textFrame.origin = CGPoint(x: imageSize.width - textSize.width - margin.x, y: imageSize.height - textSize.height - margin.y)
case .Center:
textFrame.origin = CGPoint(x: imageSize.width/2 - textSize.width/2, y: imageSize.height - textSize.height - margin.y)
}
/// Start creating the image with water mark
//imageSize = CGSize(width: (imageSize.width+textSize.width), height: (imageSize.height+textSize.height))
UIGraphicsBeginImageContext(imageSize)
self.drawInRect(CGRectMake(0, 0, imageSize.width, imageSize.height - textSize.height))
NSString(string: waterMarkText).drawInRect(textFrame, withAttributes: textAttributes)
let waterMarkedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return waterMarkedImage
}

Resources