Dissmissed UIViewController didreceivememorywarning - swift - ios

I have a custom UIImagePickerController that still, after being dismissed and the variable set to nil is receiving memory warnings, and it is causing my app to crash because of it.
Here is my UIImagePickerController
import UIKit
import MobileCoreServices
class Picker: UIImagePickerController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var myView = PickerView(frame: UIScreen.mainScreen().bounds)
var takenImages = [UIImage]()
var takenImagesThumbs = [UIImage]()
override init() {
super.init()
myView.picker = self
self.delegate = self
self.sourceType = UIImagePickerControllerSourceType.Camera
self.mediaTypes = [kUTTypeImage]
self.showsCameraControls = false
self.cameraOverlayView = myView
self.cameraCaptureMode = UIImagePickerControllerCameraCaptureMode.Photo
self.setFullscreen()
myView.viewing()
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setFullscreen(){
let screenSize = UIScreen.mainScreen().bounds.size
let scale = screenSize.height / screenSize.width*3/4
let translate = CGAffineTransformMakeTranslation(0,(screenSize.height - screenSize.width*4/3)*0.5);
let fullScreen = CGAffineTransformMakeScale(scale, scale);
self.cameraViewTransform = CGAffineTransformConcat(fullScreen, translate)
}
var endFunc:((images:[UIImage], thumbs:[UIImage]) -> Void)!
var ViewController:UIViewController!
func show(vc:UIViewController, complete: ((images:[UIImage], thumbs:[UIImage]) -> Void)) {
vc.presentViewController(self, animated: true, completion: nil)
endFunc = complete
ViewController = vc
}
var closeQueue = dispatch_queue_create("areyouareyou", nil)
func close() {
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
dispatch_async(self.closeQueue) {
self.endFunc(images: self.takenImages, thumbs: self.takenImagesThumbs)
self.takenImagesThumbs = [UIImage]()
self.takenImages = [UIImage]()
self.myView.update(self.takenImages.count)
}
}
self.removeFromParentViewController()
self.dismissViewControllerAnimated(true, completion: nil)
}
var resizequeue = dispatch_queue_create("hangingthree", nil)
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
myView.takeButton.enabled = true
let nfo = info as NSDictionary
var image:UIImage = nfo.valueForKey(UIImagePickerControllerOriginalImage) as UIImage
takenImages.append(image)
self.myView.update(self.takenImages.count)
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
dispatch_async(self.resizequeue) {
var theimg = Common.resizeImage(image, scaledToSize: CGSizeMake(UIScreen.mainScreen().bounds.width / 3, UIScreen.mainScreen().bounds.width / 3))
self.takenImagesThumbs.append(theimg)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
println(self.takenImages.count)
}
}
and here is my overlayview
import UIKit
class PickerView: UIView {
var picker:Picker!
var takeButton = UIButton()
var takeButtonPath = UIBezierPath()
var takeButtonLayer = CAShapeLayer()
var takeButtonIconLayer = CAShapeLayer()
var closeButton = UIButton()
var closeButtonBgPath = UIBezierPath()
var closeButtonBgLayer = CAShapeLayer()
var bottomBar:UIVisualEffectView!
var imageCount = UILabel()
override init() {
super.init()
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func viewing() {
var colors = Colors()
self.backgroundColor = UIColor.clearColor()
imageCount.frame = CGRectMake(62, 0, 30, 31)
imageCount.text = "0"
imageCount.textAlignment = NSTextAlignment.Center
imageCount.font = UIFont(name: "Arial-BoldMT", size: 20)
}
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
var colors = Colors()
CGContextSetLineWidth(context, 2)
CGContextSetStrokeColorWithColor(context, colors.pickerStrokeColor.CGColor)
CGContextSetFillColorWithColor(context, colors.pickerFillColor.CGColor)
var point = CGPointMake((self.bounds.width / 2), self.bounds.height - 30)
var start = CGFloat(Common.radians(0))
var end = CGFloat(Common.radians(360))
var moon = UIBezierPath()
moon.addArcWithCenter(point, radius: 45, startAngle: end, endAngle: start, clockwise: true)
moon.stroke()
moon.fill()
var left = UIBezierPath()
left.moveToPoint(CGPointMake(0, point.y))
left.addLineToPoint(CGPointMake(point.x - 45, point.y))
left.stroke()
var right = UIBezierPath()
right.moveToPoint(CGPointMake(self.bounds.width, point.y))
right.addLineToPoint(CGPointMake(point.x + 45, point.y))
right.stroke()
btnCloseing()
btnTakeing()
bottomBaring()
//add
self.addSubview(closeButton)
self.addSubview(takeButton)
}
func bottomBaring() {
var point = CGPointMake((self.bounds.width / 2), self.bounds.height - 30)
var frame = CGRectMake(0, point.y, self.bounds.width, self.bounds.height - point.y)
//blur
var blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
bottomBar = UIVisualEffectView(effect: blurEffect)
bottomBar.frame = frame
//blur add
self.addSubview(bottomBar)
//vib
var vibEffect = UIVibrancyEffect(forBlurEffect: blurEffect)
var vibView = UIVisualEffectView(effect: vibEffect)
vibView.frame = CGRectMake(0, 0, frame.width, frame.height)
//add
vibView.contentView.addSubview(imageCount)
bottomBar.contentView.addSubview(vibView)
}
func btnCloseing() {
var start = CGFloat(Common.radians(0))
var end = CGFloat(Common.radians(360))
var colors = Colors()
closeButtonBgPath.addArcWithCenter(CGPointMake(0, 0), radius: 20, startAngle: start, endAngle: end, clockwise: true)
closeButtonBgLayer.bounds = CGRectMake(-40, -40, 40, 40)
closeButtonBgLayer.path = closeButtonBgPath.CGPath
closeButtonBgLayer.fillColor = colors.pickerCloseBtnFill.CGColor
closeButtonBgLayer.strokeColor = colors.pickerStrokeColor.CGColor
closeButton.frame = CGRectMake(self.bounds.width - 50, 10, 40, 40)
closeButton.layer.addSublayer(closeButtonBgLayer)
closeButton.setTitle("X", forState: UIControlState.Normal)
closeButton.setTitleColor(colors.pickerStrokeColor, forState: UIControlState.Normal)
closeButton.titleLabel?.font = UIFont(name: "Arial-BoldMT", size: 25)
closeButton.addTarget(self, action: "closePhoto", forControlEvents: UIControlEvents.TouchDown)
}
func btnTakeing() {
var start = CGFloat(Common.radians(0))
var end = CGFloat(Common.radians(360))
var point = CGPointMake((self.bounds.width / 2), self.bounds.height - 30)
takeButtonPath.addArcWithCenter(CGPointMake(0, 0), radius: 40, startAngle: start, endAngle: end, clockwise: true)
takeButtonLayer.bounds = CGRectMake(-80, -90, 80, 80)
takeButtonLayer.path = takeButtonPath.CGPath
takeButtonLayer.fillColor = Colors().pickerTakeBtnFill.CGColor
takeButtonLayer.strokeColor = UIColor.clearColor().CGColor
takeButtonIconLayer.contents = UIImage(named: "CameraIcon")?.CGImage
takeButtonIconLayer.frame = CGRectMake(26, 30, 30, 30)
takeButton.frame = CGRectMake(point.x - 40, point.y - 50, 80, 100)
takeButton.layer.addSublayer(takeButtonLayer)
takeButton.layer.addSublayer(takeButtonIconLayer)
takeButton.addTarget(self, action: "takePhoto", forControlEvents: UIControlEvents.TouchDown)
takeButton.addTarget(self, action: "takePhotoEnd", forControlEvents: UIControlEvents.TouchUpInside)
takeButton.addTarget(self, action: "takePhotoEnd", forControlEvents: UIControlEvents.TouchUpOutside)
}
func takePhoto() {
self.takeButton.enabled = false
takeButtonLayer.fillColor = Colors().pickerTakeBtnFillClick.CGColor
picker.takePicture()
}
func takePhotoEnd() {
takeButtonLayer.fillColor = Colors().pickerTakeBtnFill.CGColor
}
func closePhoto() {
picker.close()
}
func update(count: Int) {
imageCount.text = String(count)
}
}
Anyone knows the problem or how to fix it?

Your problem is that you are subclassing UIImagePickerController which is prohibited. Read the Apple documentation:
IMPORTANT
The UIImagePickerController class supports portrait mode only. This class is intended to be used as-is and does not support subclassing. The view hierarchy for this class is private and must not be modified, with one exception. You can assign a custom view to the cameraOverlayView property and use that view to present additional information or manage the interactions between the camera interface and your code.

Related

IOS Step menu using swift

I would like to create the stepper menu in IOS using swift, But I'm facing some issues. Here are the issues.
1) Portrait and landscape stepper menu is not propper.
2) How to set default step position with the method below method, It's working when button clicked. But I want to set when menu loads the first time.
self.stepView.setSelectedPosition(index: 2)
3) If it reached the position last, I would like to change the color for complete path parentPathRect.
4) Progress animation CABasicAnimation is not like the progress bar, I want to show the animation.
5) It should not remove the selected position color when changing the orientation.
As per my organization rules should not use third-party frameworks.
Can anyone help me with the solution? Or is there any alternative solution for this?
Here is my code:
import UIKit
class ViewController: UIViewController, StepMenuDelegate {
#IBOutlet weak var stepView: StepView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.stepView.delegate = self;
self.stepView.titles = ["1", "2", "3"]
self.stepView.lineWidth = 8
self.stepView.offSet = 8
self.stepView.setSelectedPosition(index: 2)
}
func didSelectItem(atIndex index: NSInteger) {
print(index)
}
}
protocol StepMenuDelegate {
func didSelectItem(atIndex index: NSInteger)
}
class StepView: UIView {
var delegate : StepMenuDelegate!
var titles: [String] = [] {
didSet(values) {
setup()
setupItems()
}
}
var lineWidth: CGFloat = 8 {
didSet(values) {
setup()
}
}
var offSet: CGFloat = 8 {
didSet(values) {
self.itemOffset = offSet * 4
setup()
}
}
private var selectedIndex : NSInteger!
private var itemOffset : CGFloat = 8 {
didSet (value) {
setup()
setupItems()
}
}
private var path : UIBezierPath!
var selectedLayer : CAShapeLayer!
private var parentPathRect : CGRect!
override func awakeFromNib() {
super.awakeFromNib()
}
override func layoutSubviews() {
self.setup()
setupItems()
}
func setup() {
self.removeAllButtonsAndLayes()
let layer = CAShapeLayer()
self.parentPathRect = CGRect(origin: CGPoint(x: offSet, y: self.bounds.midY - (self.lineWidth/2) ), size: CGSize(width: self.bounds.width - (offSet * 2), height: lineWidth))
path = UIBezierPath(roundedRect: self.parentPathRect, cornerRadius: 2)
layer.path = path.cgPath
layer.fillColor = UIColor.orange.cgColor
layer.lineCap = .butt
layer.shadowColor = UIColor.darkGray.cgColor
layer.shadowOffset = CGSize(width: 1, height: 2)
layer.shadowOpacity = 0.1
layer.shadowRadius = 2
self.layer.addSublayer(layer)
}
func setupItems() {
removeAllButtonsAndLayes()
let itemRect = CGRect(x: self.itemOffset, y: 0, width: 34, height: 34)
let totalWidth = self.bounds.width
let itemWidth = totalWidth / CGFloat(self.titles.count);
for i in 0..<self.titles.count {
let button = UIButton()
var xPos: CGFloat = itemOffset
self.addSubview(button)
xPos += (CGFloat(i) * itemWidth);
xPos += itemOffset/3
button.translatesAutoresizingMaskIntoConstraints = false
button.leftAnchor.constraint(equalTo: self.leftAnchor, constant: xPos).isActive = true
button.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: 0).isActive = true
button.heightAnchor.constraint(equalToConstant: itemRect.height).isActive = true
button.widthAnchor.constraint(equalToConstant: itemRect.width).isActive = true
button.backgroundColor = UIColor.red
button.layer.zPosition = 1
button.layer.cornerRadius = itemRect.height/2
let name : String = self.titles[i]
button.tag = i
button.setTitle(name, for: .normal)
button.addTarget(self, action: #selector(selectedItemEvent(sender:)), for: .touchUpInside)
if self.selectedIndex != nil {
if button.tag == self.selectedIndex {
selectedItemEvent(sender: button)
}
}
}
}
#objc func selectedItemEvent(sender:UIButton) {
if self.selectedLayer != nil {
selectedLayer.removeFromSuperlayer()
}
self.delegate.didSelectItem(atIndex: sender.tag)
let fromRect = self.parentPathRect.origin
self.selectedLayer = CAShapeLayer()
let rect = CGRect(origin: fromRect, size: CGSize(width:sender.frame.origin.x - 4, height: 8))
let path = UIBezierPath(roundedRect: rect, cornerRadius: 4)
self.selectedLayer.path = path.cgPath
self.selectedLayer.lineCap = .round
self.selectedLayer.fillColor = UIColor.orange.cgColor
let animation = CABasicAnimation(keyPath: "fillColor")
animation.toValue = UIColor.blue.cgColor
animation.duration = 0.2
animation.fillMode = .forwards
animation.isRemovedOnCompletion = false
self.selectedLayer.add(animation, forKey: "fillColor")
self.layer.addSublayer(self.selectedLayer)
}
func removeAllButtonsAndLayes() {
for button in self.subviews {
if button is UIButton {
button.removeFromSuperview()
}
}
}
func setSelectedPosition(index:NSInteger) {
self.selectedIndex = index
}
}
Here I found One way to achieve the solution.!!
https://gist.github.com/DamodarGit/7f0f484708f60c996772ae28e5e1c615
Welcome to suggestions or code changes.!!

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

SwiftPages updateUI Does Not Work with Swift 3

I'm using Swiftpages. When app is opened it looks like first picture.
But app goes to background and opened different app on device, after open again my app it looks like second picture.
I updated to Swift 3, but I can't figure out the issue, I write about it on Github but no reply from them.
public class SwiftPages: UIView {
private lazy var token = 0
var containerVieww: UIView!
private var scrollView: UIScrollView!
private var topBar: UIView!
var animatedBar: UIView!
var viewControllerIDs = [String]()
private var buttonTitles = [String]()
private var buttonImages = [UIImage]()
private var pageViews = [UIViewController?]()
private var currentPage: Int = 0
// Container view position variables
private var xOrigin: CGFloat = 0
private var yOrigin: CGFloat = 64
private var distanceToBottom: CGFloat = 0
// Color variables
private var animatedBarColor = UIColor(red: 28/255, green: 95/255, blue: 185/255, alpha: 1)
private var topBarBackground = UIColor.white
private var buttonsTextColor = UIColor.gray
private var containerViewBackground = UIColor.white
// Item size variables
private var topBarHeight: CGFloat = 52
private var animatedBarHeight: CGFloat = 3
// Bar item variables
private var aeroEffectInTopBar = false //This gives the top bap a blurred effect, also overlayes the it over the VC's
private var buttonsWithImages = false
var barShadow = true
private var shadowView : UIView!
private var shadowViewGradient = CAGradientLayer()
private var buttonsTextFontAndSize = UIFont(name: "HelveticaNeue-Light", size: 20)!
private var blurView : UIVisualEffectView!
private var barButtons = [UIButton?]()
// MARK: - Positions Of The Container View API -
public func setOriginX (origin : CGFloat) { xOrigin = origin }
public func setOriginY (origin : CGFloat) { yOrigin = origin }
public func setDistanceToBottom (distance : CGFloat) { distanceToBottom = distance }
// MARK: - API's -
public func setAnimatedBarColor (color : UIColor) { animatedBarColor = color }
public func setTopBarBackground (color : UIColor) { topBarBackground = color }
public func setButtonsTextColor (color : UIColor) { buttonsTextColor = color }
public func setContainerViewBackground (color : UIColor) { containerViewBackground = color }
public func setTopBarHeight (pointSize : CGFloat) { topBarHeight = pointSize}
public func setAnimatedBarHeight (pointSize : CGFloat) { animatedBarHeight = pointSize}
public func setButtonsTextFontAndSize (fontAndSize : UIFont) { buttonsTextFontAndSize = fontAndSize}
public func enableAeroEffectInTopBar (boolValue : Bool) { aeroEffectInTopBar = boolValue}
public func enableButtonsWithImages (boolValue : Bool) { buttonsWithImages = boolValue}
public func enableBarShadow (boolValue : Bool) { barShadow = boolValue}
override public func draw(_ rect: CGRect) {
DispatchQueue.main.async {
let pagesContainerHeight = self.frame.height - self.yOrigin - self.distanceToBottom
let pagesContainerWidth = self.frame.width
// Set the notifications for an orientation change & BG mode
let defaultNotificationCenter = NotificationCenter.default
defaultNotificationCenter.addObserver(self, selector: #selector(SwiftPages.applicationWillEnterBackground), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
defaultNotificationCenter.addObserver(self, selector: #selector(SwiftPages.orientationWillChange), name: NSNotification.Name.UIApplicationWillChangeStatusBarOrientation, object: nil)
defaultNotificationCenter.addObserver(self, selector: #selector(SwiftPages.orientationDidChange), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
defaultNotificationCenter.addObserver(self, selector: #selector(SwiftPages.applicationWillEnterForeground), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
// Set the containerView, every item is constructed relative to this view
self.containerVieww = UIView(frame: CGRect(x: self.xOrigin, y: self.yOrigin, width: pagesContainerWidth, height: pagesContainerHeight))
self.containerVieww.backgroundColor = self.containerViewBackground
self.containerVieww.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(self.containerVieww)
//Add the constraints to the containerView.
if #available(iOS 9.0, *) {
let horizontalConstraint = self.containerVieww.centerXAnchor.constraint(equalTo: self.centerXAnchor)
let verticalConstraint = self.containerVieww.centerYAnchor.constraint(equalTo: self.centerYAnchor)
let widthConstraint = self.containerVieww.widthAnchor.constraint(equalTo: self.widthAnchor)
let heightConstraint = self.containerVieww.heightAnchor.constraint(equalTo: self.heightAnchor)
NSLayoutConstraint.activate([horizontalConstraint, verticalConstraint, widthConstraint, heightConstraint])
}
// Set the scrollview
if self.aeroEffectInTopBar {
self.scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: self.containerVieww.frame.size.width, height: self.containerVieww.frame.size.height))
} else {
self.scrollView = UIScrollView(frame: CGRect(x: 0, y: self.topBarHeight, width: self.containerVieww.frame.size.width, height: self.containerVieww.frame.size.height - self.topBarHeight))
}
self.scrollView.isPagingEnabled = true
self.scrollView.showsHorizontalScrollIndicator = false
self.scrollView.showsVerticalScrollIndicator = false
self.scrollView.delegate = self
self.scrollView.backgroundColor = UIColor.clear
self.scrollView.contentOffset = CGPoint(x: 0, y: 0)
self.scrollView.translatesAutoresizingMaskIntoConstraints = false
self.scrollView.isScrollEnabled = false
self.containerVieww.addSubview(self.scrollView)
// Add the constraints to the scrollview.
if #available(iOS 9.0, *) {
let leadingConstraint = self.scrollView.leadingAnchor.constraint(equalTo: self.containerVieww.leadingAnchor)
let trailingConstraint = self.scrollView.trailingAnchor.constraint(equalTo: self.containerVieww.trailingAnchor)
let topConstraint = self.scrollView.topAnchor.constraint(equalTo: self.containerVieww.topAnchor)
let bottomConstraint = self.scrollView.bottomAnchor.constraint(equalTo: self.containerVieww.bottomAnchor)
NSLayoutConstraint.activate([leadingConstraint, trailingConstraint, topConstraint, bottomConstraint])
}
// Set the top bar
self.topBar = UIView(frame: CGRect(x: 0, y: 0, width: self.containerVieww.frame.size.width, height: self.topBarHeight))
self.topBar.backgroundColor = self.topBarBackground
if self.aeroEffectInTopBar {
// Create the blurred visual effect
// You can choose between ExtraLight, Light and Dark
self.topBar.backgroundColor = UIColor.clear
let blurEffect: UIBlurEffect = UIBlurEffect(style: .light)
self.blurView = UIVisualEffectView(effect: blurEffect)
self.blurView.frame = self.topBar.bounds
self.blurView.translatesAutoresizingMaskIntoConstraints = false
self.topBar.addSubview(self.blurView)
}
self.topBar.translatesAutoresizingMaskIntoConstraints = false
self.containerVieww.addSubview(self.topBar)
// Set the top bar buttons
// Check to see if the top bar will be created with images ot text
if self.buttonsWithImages {
var buttonsXPosition: CGFloat = 0
for (index, image) in self.buttonImages.enumerated() {
let frame = CGRect(x: buttonsXPosition, y: 0, width: self.containerVieww.frame.size.width / CGFloat(self.viewControllerIDs.count), height: self.topBarHeight)
let barButton = UIButton(frame: frame)
barButton.backgroundColor = UIColor.clear
barButton.imageView?.contentMode = .scaleAspectFit
barButton.setImage(image, for: .normal)
barButton.tag = index
barButton.addTarget(self, action: #selector(SwiftPages.barButtonAction), for: .touchUpInside)
self.topBar.addSubview(barButton)
self.barButtons.append(barButton)
buttonsXPosition += self.containerVieww.frame.size.width / CGFloat(self.viewControllerIDs.count)
}
} else {
var buttonsXPosition: CGFloat = 0
for (index, title) in self.buttonTitles.enumerated() {
let frame = CGRect(x: buttonsXPosition, y: 0, width: self.containerVieww.frame.size.width / CGFloat(self.viewControllerIDs.count), height: self.topBarHeight)
let barButton = UIButton(frame: frame)
barButton.backgroundColor = UIColor.clear
barButton.titleLabel!.font = self.buttonsTextFontAndSize
barButton.setTitle(title, for: .normal)
barButton.setTitleColor(self.buttonsTextColor, for: .normal)
barButton.tag = index
barButton.addTarget(self, action: #selector(SwiftPages.barButtonAction), for: .touchUpInside)
self.topBar.addSubview(barButton)
self.barButtons.append(barButton)
buttonsXPosition += self.containerVieww.frame.size.width / CGFloat(self.viewControllerIDs.count)
}
}
// Set up the animated UIView
self.animatedBar = UIView(frame: CGRect(x: 0, y: self.topBarHeight - self.animatedBarHeight + 1, width: (self.containerVieww.frame.size.width / CGFloat(self.viewControllerIDs.count)) * 0.8, height: self.animatedBarHeight))
self.animatedBar.center.x = self.containerVieww.frame.size.width / CGFloat(self.viewControllerIDs.count << 1)
self.animatedBar.backgroundColor = self.animatedBarColor
self.containerVieww.addSubview(self.animatedBar)
// Add the bar shadow (set to true or false with the barShadow var)
if self.barShadow {
self.shadowView = UIView(frame: CGRect(x: 0, y: self.topBarHeight, width: self.containerVieww.frame.size.width, height: 4))
self.shadowViewGradient.frame = self.shadowView.bounds
self.shadowViewGradient.colors = [UIColor(red: 150/255, green: 150/255, blue: 150/255, alpha: 0.28).cgColor, UIColor.clear.cgColor]
self.shadowView.layer.insertSublayer(self.shadowViewGradient, at: 0)
self.containerVieww.addSubview(self.shadowView)
}
let pageCount = self.viewControllerIDs.count
// Fill the array containing the VC instances with nil objects as placeholders
for _ in 0..<pageCount {
self.pageViews.append(nil)
}
// Defining the content size of the scrollview
let pagesScrollViewSize = self.scrollView.frame.size
self.scrollView.contentSize = CGSize(width: pagesScrollViewSize.width * CGFloat(pageCount), height: pagesScrollViewSize.height)
// Load the pages to show initially
self.loadVisiblePages()
// Do the initial alignment of the subViews
self.alignSubviews()
}
}
// MARK: - Initialization Functions -
public func initializeWithVCIDsArrayAndButtonTitlesArray (VCIDsArray: [String], buttonTitlesArray: [String]) {
// Important - Titles Array must Have The Same Number Of Items As The viewControllerIDs Array
if VCIDsArray.count == buttonTitlesArray.count {
viewControllerIDs = VCIDsArray
buttonTitles = buttonTitlesArray
buttonsWithImages = false
} else {
print("Initilization failed, the VC ID array count does not match the button titles array count.")
}
}
public func initializeWithVCIDsArrayAndButtonImagesArray (VCIDsArray: [String], buttonImagesArray: [UIImage]) {
// Important - Images Array must Have The Same Number Of Items As The viewControllerIDs Array
if VCIDsArray.count == buttonImagesArray.count {
viewControllerIDs = VCIDsArray
buttonImages = buttonImagesArray
buttonsWithImages = true
} else {
print("Initilization failed, the VC ID array count does not match the button images array count.")
}
}
public func loadPage(page: Int) {
// If it's outside the range of what you have to display, then do nothing
guard page >= 0 && page < viewControllerIDs.count else { return }
// Do nothing if the view is already loaded.
guard pageViews[page] == nil else { return }
print("Loading Page \(page)")
// The pageView instance is nil, create the page
var frame = scrollView.bounds
frame.origin.x = frame.size.width * CGFloat(page)
frame.origin.y = 0.0
// Look for the VC by its identifier in the storyboard and add it to the scrollview
let newPageView = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: viewControllerIDs[page])
newPageView.view.frame = frame
scrollView.addSubview(newPageView.view)
// Replace the nil in the pageViews array with the VC just created
pageViews[page] = newPageView
}
public func loadVisiblePages() {
// First, determine which page is currently visible
let pageWidth = scrollView.frame.size.width
let page = Int(floor((scrollView.contentOffset.x * 2.0 + pageWidth) / (pageWidth * 2.0)))
// Work out which pages you want to load
let firstPage = page - 1
let lastPage = page + 1
// Load pages in our range
for index in firstPage...lastPage {
loadPage(page: index)
}
}
public func barButtonAction(sender: UIButton?) {
let index = sender!.tag
let pagesScrollViewSize = scrollView.frame.size
scrollView.setContentOffset(CGPoint(x: pagesScrollViewSize.width * CGFloat(index), y: 0), animated: true)
currentPage = index
}
// MARK: - Orientation Handling Functions -
public func alignSubviews() {
let pageCount = viewControllerIDs.count
// Setup the new frames
scrollView.contentSize = CGSize(width: CGFloat(pageCount) * scrollView.bounds.size.width, height: scrollView.bounds.size.height)
topBar.frame = CGRect(x: 0, y: 0, width: containerVieww.frame.size.width, height: topBarHeight)
blurView?.frame = topBar.bounds
animatedBar.frame.size = CGSize(width: (containerVieww.frame.size.width / (CGFloat)(viewControllerIDs.count)) * 0.8, height: animatedBarHeight)
if barShadow {
shadowView.frame.size = CGSize(width: containerVieww.frame.size.width, height: 4)
shadowViewGradient.frame = shadowView.bounds
}
// Set the new frame of the scrollview contents
for (index, controller) in pageViews.enumerated() {
controller?.view.frame = CGRect(x: CGFloat(index) * scrollView.bounds.size.width, y: 0, width: scrollView.bounds.size.width, height: scrollView.bounds.size.height)
}
// Set the new frame for the top bar buttons
var buttonsXPosition: CGFloat = 0
for button in barButtons {
button?.frame = CGRect(x: buttonsXPosition, y: 0, width: containerVieww.frame.size.width / CGFloat(viewControllerIDs.count), height: topBarHeight)
buttonsXPosition += containerVieww.frame.size.width / CGFloat(viewControllerIDs.count)
}
}
func applicationWillEnterBackground() {
//Save the current page
currentPage = Int(scrollView.contentOffset.x / scrollView.bounds.size.width)
print("Haydar")
}
func orientationWillChange() {
//Save the current page
currentPage = Int(scrollView.contentOffset.x / scrollView.bounds.size.width)
}
func orientationDidChange() {
//Update the view
alignSubviews()
scrollView.contentOffset = CGPoint(x: CGFloat(currentPage) * scrollView.frame.size.width, y: 0)
}
func applicationWillEnterForeground() {
alignSubviews()
scrollView.contentOffset = CGPoint(x: CGFloat(currentPage) * scrollView.frame.size.width, y: 0)
initializeWithVCIDsArrayAndButtonTitlesArray(VCIDsArray: buttonTitles, buttonTitlesArray: buttonTitles)
print("ForegroundHound")
}
public func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
let previousPage : NSInteger = currentPage
let pageWidth : CGFloat = scrollView.frame.size.width
let fractionalPage = scrollView.contentOffset.x / pageWidth
let page : NSInteger = Int(round(fractionalPage))
if (previousPage != page) {
currentPage = page;
}
}
deinit {
NotificationCenter.default.removeObserver(self)
print("deinittta")
}
}
extension SwiftPages: UIScrollViewDelegate {
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
// Load the pages that are now on screen
loadVisiblePages()
// The calculations for the animated bar's movements
// The offset addition is based on the width of the animated bar (button width times 0.8)
let offsetAddition = (containerVieww.frame.size.width / CGFloat(viewControllerIDs.count)) * 0.1
animatedBar.frame = CGRect(x: (offsetAddition + (scrollView.contentOffset.x / CGFloat(viewControllerIDs.count))), y: animatedBar.frame.origin.y, width: animatedBar.frame.size.width, height: animatedBar.frame.size.height)
}
}

How to create a new class from UIVisualEffectView and UIActivityIndicatorView

I've made a busy indicator that works really well, so long as it's in the ViewController I want to display the indicator in. I attempted to move this over to a new class of type UIView, but can't get anything to appear in the ViewController.
This is the working code, that is not it's own type:
//Create a busy indicator that can be shown by changing a single variable
var blur: UIVisualEffectView?
var spinner: UIActivityIndicatorView?
var showingActivity: Bool = false {
didSet{
switch showingActivity {
case true:
blur = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Dark))
blur!.frame = CGRectMake(100, 100, 150, 150)
blur!.center = self.view.center
blur!.layer.cornerRadius = 10
blur!.clipsToBounds = true
self.view.addSubview(blur!)
spinner = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
spinner!.frame = CGRectMake(0, 0, 50, 50)
spinner!.center = self.view.center
spinner!.hidesWhenStopped = true
spinner!.startAnimating()
self.view.addSubview(spinner!)
UIApplication.sharedApplication().networkActivityIndicatorVisible = true //network activity option
case false:
blur?.removeFromSuperview()
spinner?.removeFromSuperview()
blur = nil
spinner = nil
UIApplication.sharedApplication().networkActivityIndicatorVisible = false //network activity option
default: break
}
}
}
func toggleNetworkActivity() {
showingActivity = !showingActivity
}
This is the code that doesn't seem to create anything.
class busy : UIView {
var blur = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Dark))
var spinner = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
init() {
let frame = CGRect(x: 0, y: 0, width: 300, height: 300)
super.init(frame: frame)
blur.frame = CGRectMake(100, 100, 150, 150)
blur.center = self.center
blur.layer.cornerRadius = 10
blur.clipsToBounds = true
spinner.frame = CGRectMake(0, 0, 50, 50)
spinner.center = self.center
spinner.hidesWhenStopped = true
spinner.startAnimating()
self.setNeedsDisplay()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
And in ViewDidLoad:
var test = busy()
test.center = self.view.center
self.view.addSubview(test)
Figured it out. Here is the code, if anyone is interested. But, is this the right way to do this kind of task?
class busy : UIView {
private var blur = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Dark))
private var spinner = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
var isActive: Bool = false
override init (frame : CGRect) {
super.init(frame : frame)
}
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
func startActivity() {
let x = UIScreen.mainScreen().bounds.width/2
let y = UIScreen.mainScreen().bounds.height/2
blur.frame = CGRectMake(100, 100, 150, 150)
blur.layer.cornerRadius = 10
blur.center = CGPoint(x: x, y: y)
blur.clipsToBounds = true
spinner.frame = CGRectMake(0, 0, 50, 50)
spinner.hidden = false
spinner.center = CGPoint(x: x, y: y)
spinner.startAnimating()
super.addSubview(blur)
super.addSubview(spinner)
isActive = true
}
func stopActivity() {
blur.removeFromSuperview()
spinner.removeFromSuperview()
isActive = false
}
}
And then in use:
#IBAction func toggle() {
if test.isActive {
test.stopActivity()
test.removeFromSuperview()
println("Stopping")
} else {
test.startActivity()
self.view.addSubview(test)
println("Starting")
}
}

How to create a Scroll View with a page control using swift? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
I am trying to create a Page View controller with numbers of view. I want a simple code sample that will use UIPageViewController.
import UIKit
class DummyVC: UIViewController, UIScrollViewDelegate {
let scrollView = UIScrollView(frame: CGRect(x:0, y:0, width:320,height: 300))
var colors:[UIColor] = [UIColor.red, UIColor.blue, UIColor.green, UIColor.yellow]
var frame: CGRect = CGRect(x:0, y:0, width:0, height:0)
var pageControl : UIPageControl = UIPageControl(frame: CGRect(x:50,y: 300, width:200, height:50))
override func viewDidLoad() {
super.viewDidLoad()
configurePageControl()
scrollView.delegate = self
scrollView.isPagingEnabled = true
self.view.addSubview(scrollView)
for index in 0..<4 {
frame.origin.x = self.scrollView.frame.size.width * CGFloat(index)
frame.size = self.scrollView.frame.size
let subView = UIView(frame: frame)
subView.backgroundColor = colors[index]
self.scrollView .addSubview(subView)
}
self.scrollView.contentSize = CGSize(width:self.scrollView.frame.size.width * 4,height: self.scrollView.frame.size.height)
pageControl.addTarget(self, action: #selector(self.changePage(sender:)), for: UIControlEvents.valueChanged)
}
func configurePageControl() {
// The total number of pages that are available is based on how many available colors we have.
self.pageControl.numberOfPages = colors.count
self.pageControl.currentPage = 0
self.pageControl.tintColor = UIColor.red
self.pageControl.pageIndicatorTintColor = UIColor.black
self.pageControl.currentPageIndicatorTintColor = UIColor.green
self.view.addSubview(pageControl)
}
// MARK : TO CHANGE WHILE CLICKING ON PAGE CONTROL
func changePage(sender: AnyObject) -> () {
let x = CGFloat(pageControl.currentPage) * scrollView.frame.size.width
scrollView.setContentOffset(CGPoint(x:x, y:0), animated: true)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
pageControl.currentPage = Int(pageNumber)
}
}
For lazy coder this is the Swift 3 implementation based on That lazy iOS Guy 웃's answer
import UIKit
class ViewController: UIViewController,UIScrollViewDelegate {
let scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: 320, height: 300))
var colors:[UIColor] = [UIColor.red, UIColor.blue, UIColor.green, UIColor.yellow]
var frame: CGRect = CGRect(x: 0, y: 0, width: 0, height: 0)
var pageControl : UIPageControl = UIPageControl(frame:CGRect(x: 50, y: 300, width: 200, height: 50))
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
configurePageControl()
scrollView.delegate = self
self.view.addSubview(scrollView)
for index in 0..<4 {
frame.origin.x = self.scrollView.frame.size.width * CGFloat(index)
frame.size = self.scrollView.frame.size
let subView = UIView(frame: frame)
subView.backgroundColor = colors[index]
self.scrollView .addSubview(subView)
}
self.scrollView.isPagingEnabled = true
self.scrollView.contentSize = CGSize(width: self.scrollView.frame.size.width * 4, height: self.scrollView.frame.size.height)
pageControl.addTarget(self, action: #selector(self.changePage(sender:)), for: UIControlEvents.valueChanged)
}
func configurePageControl() {
// The total number of pages that are available is based on how many available colors we have.
self.pageControl.numberOfPages = colors.count
self.pageControl.currentPage = 0
self.pageControl.tintColor = UIColor.red
self.pageControl.pageIndicatorTintColor = UIColor.black
self.pageControl.currentPageIndicatorTintColor = UIColor.green
self.view.addSubview(pageControl)
}
// MARK : TO CHANGE WHILE CLICKING ON PAGE CONTROL
func changePage(sender: AnyObject) -> () {
let x = CGFloat(pageControl.currentPage) * scrollView.frame.size.width
scrollView.setContentOffset(CGPoint(x: x,y :0), animated: true)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
pageControl.currentPage = Int(pageNumber)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Swift 3 - Horizontal image scroll
import UIKit
class pageenabled: UIViewController,UIScrollViewDelegate
{
let imagelist = ["img1.jpg", "photo1.jpg", "photo3.jpg", "photo4.jpg", "photo5.jpg"]
var scrollView = UIScrollView()
var pageControl : UIPageControl = UIPageControl(frame:CGRect(x: 50, y: 300, width: 200, height: 50))
var yPosition:CGFloat = 0
var scrollViewContentSize:CGFloat=0;
override func viewDidLoad() {
super.viewDidLoad()
scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 300))
configurePageControl()
scrollView.delegate = self
self.view.addSubview(scrollView)
for i in stride(from: 0, to: imagelist.count, by: 1) {
var frame = CGRect.zero
frame.origin.x = self.scrollView.frame.size.width * CGFloat(i)
frame.origin.y = 0
frame.size = self.scrollView.frame.size
self.scrollView.isPagingEnabled = true
let myImage:UIImage = UIImage(named: imagelist[i])!
let myImageView:UIImageView = UIImageView()
myImageView.image = myImage
myImageView.contentMode = UIViewContentMode.scaleAspectFit
myImageView.frame = frame
scrollView.addSubview(myImageView)
}
self.scrollView.contentSize = CGSize(width: self.scrollView.frame.size.width * CGFloat(imagelist.count), height: self.scrollView.frame.size.height)
pageControl.addTarget(self, action: Selector(("changePage:")), for: UIControlEvents.valueChanged)
// Do any additional setup after loading the view.
}
func configurePageControl() {
// The total number of pages that are available is based on how many available colors we have.
self.pageControl.numberOfPages = imagelist.count
self.pageControl.currentPage = 0
self.pageControl.tintColor = UIColor.red
self.pageControl.pageIndicatorTintColor = UIColor.black
self.pageControl.currentPageIndicatorTintColor = UIColor.green
self.view.addSubview(pageControl)
}
// MARK : TO CHANGE WHILE CLICKING ON PAGE CONTROL
func changePage(sender: AnyObject) -> () {
let x = CGFloat(pageControl.currentPage) * scrollView.frame.size.width
scrollView.setContentOffset(CGPoint(x: x,y :0), animated: true)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
pageControl.currentPage = Int(pageNumber)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
In Swift 3.0
craeate iboutlets through story board for scrollview and pagecontroller.
#IBOutlet weak var imgScrollView: UIScrollView!
#IBOutlet weak var imgPageController: UIPageControl!
var sliderImagesArray = NSMutableArray()
in viewdidload method write this code
sliderImagesArray = ["https://images.unsplash.com/photo-1432679963831-2dab49187847?w=1080","https://images.unsplash.com/photo-1447746249824-4be4e1b76d66?w=1080", "https://images.unsplash.com/photo-1463595373836-6e0b0a8ee322?w=1080"]
imgScrollView.delegate = self
for i in 0..<sliderImagesArray.count {
var imageView : UIImageView
let xOrigin = self.imgScrollView.frame.size.width * CGFloat(i)
imageView = UIImageView(frame: CGRect(x: xOrigin, y: 0, width: self.imgScrollView.frame.size.width, height: self.imgScrollView.frame.size.height))
imageView.isUserInteractionEnabled = true
let urlStr = sliderImagesArray.object(at: i)
print(imgScrollView,imageView, urlStr)
imageView.sd_setImage(with: URL(string: urlStr as! String), placeholderImage: UIImage(named: "placeholder.png"))
imageView .contentMode = UIViewContentMode.scaleToFill
self.imgScrollView.addSubview(imageView)
}
self.imgScrollView.isPagingEnabled = true
self.imgScrollView.bounces = false
self.imgScrollView.showsVerticalScrollIndicator = false
self.imgScrollView.showsHorizontalScrollIndicator = false
self.imgScrollView.contentSize = CGSize(width:
self.imgScrollView.frame.size.width * CGFloat(sliderImagesArray.count), height: self.imgScrollView.frame.size.height)
imgPageController.addTarget(self, action: #selector(self.changePage(sender:)), for: UIControlEvents.valueChanged)
self.imgPageController.numberOfPages = sliderImagesArray.count
self.imgPageController.currentPage = 0
self.imgPageController.tintColor = UIColor.red
self.imgPageController.pageIndicatorTintColor = UIColor.black
self.imgPageController.currentPageIndicatorTintColor = UIColor.blue
after that implement scrollview delegate methods
func changePage(sender: AnyObject) -> () {
let x = CGFloat(imgPageController.currentPage) * imgScrollView.frame.size.width
imgScrollView.setContentOffset(CGPoint(x: x,y :0), animated: true)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageNumber = round(imgScrollView.contentOffset.x / imgScrollView.frame.size.width)
imgPageController.currentPage = Int(pageNumber)
}
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var imageViewBottomConstraint: NSLayoutConstraint!
#IBOutlet weak var imageViewLeadingConstraint: NSLayoutConstraint!
#IBOutlet weak var imageViewTopConstraint: NSLayoutConstraint!
#IBOutlet weak var imageViewTrailingConstraint: NSLayoutConstraint!
extension ZoomedPhotoViewController: UIScrollViewDelegate {
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return imageView
}
}
private func updateMinZoomScaleForSize(size: CGSize) {
let widthScale = size.width / imageView.bounds.width
let heightScale = size.height / imageView.bounds.height
let minScale = min(widthScale, heightScale)
scrollView.minimumZoomScale = minScale
scrollView.zoomScale = minScale
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
updateMinZoomScaleForSize(view.bounds.size)
}
private func updateConstraintsForSize(size: CGSize) {
let yOffset = max(0, (size.height - imageView.frame.height) / 2)
imageViewTopConstraint.constant = yOffset
imageViewBottomConstraint.constant = yOffset
let xOffset = max(0, (size.width - imageView.frame.width) / 2)
imageViewLeadingConstraint.constant = xOffset
imageViewTrailingConstraint.constant = xOffset
view.layoutIfNeeded()
}
func scrollViewDidZoom(scrollView: UIScrollView) {
updateConstraintsForSize(view.bounds.size)
}
import UIKit
public class PhotoCommentViewController: UIViewController {
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var nameTextField: UITextField!
public var photoName: String!
override public func viewDidLoad() {
super.viewDidLoad()
if let photoName = photoName {
self.imageView.image = UIImage(named: photoName)
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let cell = sender as? UICollectionViewCell,
indexPath = collectionView?.indexPathForCell(cell),
photoCommentViewController = segue.destinationViewController as? PhotoCommentViewController {
photoCommentViewController.photoName = "photo\(indexPath.row + 1)"
}
}
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: #selector(PhotoCommentViewController.keyboardWillShow(_:)),
name: UIKeyboardWillShowNotification,
object: nil
)
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: #selector(PhotoCommentViewController.keyboardWillHide(_:)),
name: UIKeyboardWillHideNotification,
object: nil
)
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func adjustInsetForKeyboardShow(show: Bool, notification: NSNotification) {
guard let value = notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue else { return }
let keyboardFrame = value.CGRectValue()
let adjustmentHeight = (CGRectGetHeight(keyboardFrame) + 20) * (show ? 1 : -1)
scrollView.contentInset.bottom += adjustmentHeight
scrollView.scrollIndicatorInsets.bottom += adjustmentHeight
}
func keyboardWillShow(notification: NSNotification) {
adjustInsetForKeyboardShow(true, notification: notification)
}
func keyboardWillHide(notification: NSNotification) {
adjustInsetForKeyboardShow(false, notification: notification)
}
#IBAction func hideKeyboard(sender: AnyObject) {
nameTextField.endEditing(true)
}
public var photoIndex: Int!
import UIKit
class ManagePageViewController: UIPageViewController {
var photos = ["photo1", "photo2", "photo3", "photo4", "photo5"]
var currentIndex: Int!
override func viewDidLoad() {
super.viewDidLoad()
dataSource = self
// 1
if let viewController = viewPhotoCommentController(currentIndex ?? 0) {
let viewControllers = [viewController]
// 2
setViewControllers(
viewControllers,
direction: .Forward,
animated: false,
completion: nil
)
}
}
func viewPhotoCommentController(index: Int) -> PhotoCommentViewController? {
if let storyboard = storyboard,
page = storyboard.instantiateViewControllerWithIdentifier("PhotoCommentViewController")
as? PhotoCommentViewController {
page.photoName = photos[index]
page.photoIndex = index
return page
}
return nil
}
}

Resources