I am new to iOS and Swift. I am trying to add a background image for a slide right effect. I want that image to stick to the right of the screen no matter what orientation. The image will always be a set size (now its (382x145px). How can I adjust it on landscape orientation so that the picture stays to the right.
Here is my custom view cell class.
class CustomRouteViewCell: UITableViewCell {
#IBOutlet var downImage: UIImageView!
#IBOutlet var downTime: UILabel!
#IBOutlet weak var leadingSpaceConstraint: NSLayoutConstraint!
#IBOutlet weak var trailingSpaceConstraint: NSLayoutConstraint!
#IBOutlet var locationTitle: UILabel!
#IBOutlet weak var panView: UIView!
#IBOutlet var timerLabel: UILabel!
var indexRow: Int = 0
var timeInterval: Int = 0
override func awakeFromNib() {
super.awakeFromNib()
self.selectedBackgroundView = nil
var img = UIImage(named: "tableSwipeArrow.png")!
self.panView.backgroundColor = UIColor(patternImage: img)
if self.respondsToSelector(Selector("setLayoutMargins:")) {
layoutMargins = UIEdgeInsetsZero
}
if self.respondsToSelector(Selector("setPreservesSuperviewLayoutMargins:")) {
preservesSuperviewLayoutMargins = false
}
var panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "handlePanGesture:")
panGestureRecognizer.delegate = self
addGestureRecognizer(panGestureRecognizer)
}
func handlePanGesture(recognizer: UIPanGestureRecognizer) {
switch(recognizer.state) {
case UIGestureRecognizerState.Changed:
var translation = recognizer.translationInView(recognizer.view!)
var little = CGFloat(trailingSpaceConstraint.constant + translation.x * -1)
trailingSpaceConstraint.constant = fmax(0, little)
leadingSpaceConstraint.constant = fmin(0, leadingSpaceConstraint.constant + translation.x)
recognizer.setTranslation(CGPointZero, inView: recognizer.view!)
timeInterval = Int(trailingSpaceConstraint.constant / 30) * 5
timerLabel.text! = "\(timeInterval)"
case UIGestureRecognizerState.Ended, UIGestureRecognizerState.Cancelled:
var refreshAlert = Alarm.getReminderView(self.timeInterval, view: self.parentViewController!.view)
self.parentViewController?.presentViewController(refreshAlert, animated: true, completion: nil)
leadingSpaceConstraint.constant = 0
trailingSpaceConstraint.constant = 0
UIView.animateWithDuration(0.25, animations: { () -> Void in
self.layoutIfNeeded()
})
default:
trailingSpaceConstraint.constant = 0
leadingSpaceConstraint.constant = 0
}
}
}
extension CustomRouteViewCell: UIGestureRecognizerDelegate
{
override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer.isKindOfClass(UIPanGestureRecognizer) {
var velocity = (gestureRecognizer as! UIPanGestureRecognizer).velocityInView(gestureRecognizer.view!)
return fabs(velocity.x) > fabs(velocity.y)
}
return true;
}
}
Use auto layout to link the position of the images.
In your case you can connect the trailing of the background image with the container view.
Hold Control on image and link the Trailing Attribute with the main view
Just adjust the constant to 0.
Related
Main.StoryBoard in this way
class ForgotPasswordContainerControl: UIViewController {
#IBOutlet var screenStep1: UIView?
#IBOutlet var screenStep2: UIView?
#IBOutlet var screenStep3: UIView?
override func viewDidLoad() {
super.viewDidLoad()
self.screenStep1?.alpha = 1.0
self.screenStep2?.alpha = 0.0
self.screenStep3?.alpha = 0.0
}
#IBAction func step1ButtonClick(_ sender: UIButton) {
UIView.animate(withDuration: 0.5, animations: {
self.screenStep1?.alpha = 0.0
self.screenStep2?.alpha = 1.0
self.screenStep3?.alpha = 0.0
print("clicked button1 ")
})
print("clicked button2 ")
}
}
My code is working in viewdDidLoad, clicking the button prints is working
but Alpha does not work, how can i do?
I have a UIScrollView Hooked up to 2 View Controllers. like this
let V1 = self.storyboard?.instantiateViewControllerWithIdentifier("HomeScreen") as UIViewController!
//Add initialized view to main view and its scroll view and also set bounds
self.addChildViewController(V1)
self.scrollVieww.addSubview(V1.view)
V1.didMoveToParentViewController(self)
V1.view.frame = scrollVieww.bounds
//Initialize using Unique ID for the View
let V2 = self.storyboard?.instantiateViewControllerWithIdentifier("MainScreen") as UIViewController!
//Add initialized view to main view and its scroll view also set bounds
self.addChildViewController(V2)
self.scrollVieww.addSubview(V2.view)
V2.didMoveToParentViewController(self)
V2.view.frame = scrollVieww.bounds
//Create frame for the view and define its urigin point with respect to View 1
var V2Frame: CGRect = V2.view.frame
V2Frame.origin.x = self.view.frame.width
V2.view.frame = V2Frame
//The width is set here as we are dealing with Horizontal Scroll
//The Width is x3 as there are 3 sub views in all
self.scrollVieww.contentSize = CGSizeMake((self.view.frame.width) * 2, (self.view.frame.height))
Now i can use The ScrollView Delegate Method which is written inside this class.
So now i went up to my class Main_Screen and subclass it with UIScrollViewDelegate.
Code for Main_Screen Class
import UIKit
public class Main_Screen: UIViewController , UIScrollViewDelegate {
#IBOutlet weak var aboutMebtn: UIButton!
#IBOutlet weak var studybtn: UIButton!
#IBOutlet weak var appsbtn: UIButton!
#IBOutlet weak var skillsbtn: UIButton!
var scrollView : UIScrollView!
#IBOutlet var avatarImageView: UIImageView!
weak var pageControl: UIPageControl!
var mainRead : Bool = false
override public func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// Making the view round
for v : UIView in self.view.subviews {
if v.tag != 1 {
v.layer.cornerRadius = v.frame.size.width/2
v.layer.masksToBounds = true
}
}
}
public func animate(){
// I get a fatal error here
var buttons : Array<UIButton> = [aboutMebtn , studybtn , appsbtn , skillsbtn]
avatarImageView.alpha = 0.0
avatarImageView.transform = CGAffineTransformMakeScale(1.25, 1.25)
UIView.animateWithDuration(1.0, delay: 1.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: .CurveEaseIn, animations: { () -> Void in
self.avatarImageView.alpha = 1.0
self.avatarImageView.transform = CGAffineTransformMakeScale(0.75, 0.75)
}, completion: nil)
}
public func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
if(scrollView.contentOffset.x == self.view.frame.size.width * 1 ){
print("Main is read")
}
}
But the method of UIScrollView Delegate wont execute. i can do it in ViewController but i cant as i want to run the animate function Above on the scrollViewDidEndDeclerating Method
you must assign your view controller as UIScrollView delegate
self.scrollVieww.delegate = self;
you probably miss it.
you can make it inside viewDidLoad
I am making a calculator app in iOS 9, Swift and with Xcode 7 and I would like to know how to create UIButtons when the user switches to landscape mode only. Adding more operators to the left of the number and AC Button and changing the constraints, shifting the buttons over to make room for the new ones. The basic calculator for iOS does this and I'm wondering how??
I'm new to iOS development and I have been web browsing to only find an overriding function called: viewWillTransitionToSize(). Is this the right function to do this sort of thing?
Also, everytime I enter the landscape view, another button gets created. How can I stop this from happening?
Attached is my programmatic creation of the UIbutton and the function I listed above.
Sorry for the array of questions/problems. I am having difficulties finding tutorials or help on this issue. Any guidance or solution will be helpful. Thank you so much.
ViewController.swift
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var outputDisplay: UILabel!
#IBOutlet weak var number7: UIButton!
#IBOutlet weak var number1: UIButton!
#IBOutlet weak var number2: UIButton!
#IBOutlet weak var number3: UIButton!
#IBOutlet weak var number4: UIButton!
#IBOutlet weak var number5: UIButton!
#IBOutlet weak var number6: UIButton!
#IBOutlet weak var number9: UIButton!
#IBOutlet weak var number8: UIButton!
#IBOutlet weak var numberZero: UIButton!
#IBOutlet weak var decimalPoint: UIButton!
#IBOutlet weak var plusMinusToggle: UIButton!
#IBOutlet weak var acClear: UIButton!
#IBOutlet weak var equalButton: UIButton!
#IBOutlet weak var multiply: UIButton!
#IBOutlet weak var divide: UIButton!
#IBOutlet weak var subtraction: UIButton!
#IBOutlet weak var addition: UIButton!
#IBOutlet weak var deletion: UIButton!
#IBOutlet weak var squareRoot: UIButton!
var typing:Bool = false
var firstNumber: Float = 0.0
var secondNumber: Float = 0.0
var operation:String = ""
var result: Float = 0.0
var valueToPass: Float = 0.0
override func viewDidLoad() {
super.viewDidLoad()
number1.layer.cornerRadius = number1.bounds.size.width / 8.0
number2.layer.cornerRadius = number2.bounds.size.width / 8.0
number3.layer.cornerRadius = number3.bounds.size.width / 8.0
number4.layer.cornerRadius = number4.bounds.size.width / 8.0
number5.layer.cornerRadius = number5.bounds.size.width / 8.0
number6.layer.cornerRadius = number6.bounds.size.width / 8.0
number7.layer.cornerRadius = number7.bounds.size.width / 8.0
number8.layer.cornerRadius = number8.bounds.size.width / 8.0
number9.layer.cornerRadius = number9.bounds.size.width / 8.0
numberZero.layer.cornerRadius = numberZero.bounds.size.width / 8.0
equalButton.layer.cornerRadius = equalButton.bounds.size.width / 8.0
deletion.layer.cornerRadius = deletion.bounds.size.width / 8.0
plusMinusToggle.layer.cornerRadius = plusMinusToggle.bounds.size.width / 8.0
decimalPoint.layer.cornerRadius = decimalPoint.bounds.size.width / 8.0
acClear.layer.cornerRadius = acClear.bounds.size.width / 8.0
addition.layer.cornerRadius = addition.bounds.size.width / 8.0
divide.layer.cornerRadius = divide.bounds.size.width / 8.0
multiply.layer.cornerRadius = multiply.bounds.size.width / 8.0
subtraction.layer.cornerRadius = subtraction.bounds.size.width / 8.0
squareRoot.layer.cornerRadius = squareRoot.bounds.size.width / 8.0
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
if (UIDevice.currentDevice().orientation.isLandscape) {
print("Device in Lanscape")
let newButton1 = UIButton(type: UIButtonType.System) as UIButton
newButton1.frame = CGRectMake(100, 100, 100, 50)
newButton1.backgroundColor = UIColor.whiteColor()
newButton1.center = CGPoint(x: number1.frame.width, y: number1.frame.height)
newButton1.layer.cornerRadius = newButton1.bounds.size.width / 8.0
self.view.addSubview(newButton1)
}
else{}
}
#IBAction func numberPressed(sender: AnyObject) {
// set the variable "number" to whichever number the user presses
let number = sender.currentTitle!
if typing {
outputDisplay.text = outputDisplay.text! + String(number!)
} else {
outputDisplay.text = number!
}
typing = true
}
#IBAction func calculationPressed(sender: AnyObject) {
typing = false
firstNumber = Float(outputDisplay.text!)!
operation = sender.currentTitle!!
}
#IBAction func equalPressed(sender: AnyObject) {
secondNumber = Float(outputDisplay.text!)!
typing = false
//arithmetic operations
if operation == "+" {
result = firstNumber + secondNumber
}
else if operation == "-" {
result = firstNumber - secondNumber
}
else if operation == "✕" {
result = firstNumber * secondNumber
}
else if operation == "÷" {
result = firstNumber / secondNumber
}
// else if operation == "%" {
// result = (firstNumber * secondNumber) / 100
// }
else if operation == "√" {
result = sqrt(firstNumber)
}
outputDisplay.text = "\(result)"
}
#IBAction func squareRoot(sender: AnyObject) {
result = sqrt(Float(outputDisplay.text!)!)
outputDisplay.text = "\(result)"
}
#IBAction func deletePressed(sender: AnyObject) {
if outputDisplay.text!.characters.count != 0 {
outputDisplay.text = outputDisplay.text!.substringToIndex(outputDisplay.text!.endIndex.predecessor())
}
else{
outputDisplay.text = "0"
}
}
#IBAction func plusMinus(sender: AnyObject) {
if( outputDisplay.text![outputDisplay.text!.startIndex] == "-"){
outputDisplay.text!.removeAtIndex(outputDisplay.text!.startIndex)
}else{
outputDisplay.text!.insert("-", atIndex: outputDisplay.text!.startIndex)
}
}
#IBAction func decimal(sender: AnyObject) {
let decimal = sender.currentTitle!
outputDisplay.text = outputDisplay.text! + decimal!
}
#IBAction func clear(sender: AnyObject) {
result = 0
firstNumber = 0
secondNumber = 0
outputDisplay.text = "0"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I would do this using Size Classes. You can design different layouts and button arrangements in storyboard using the different size classes. If this application is on the iPhone, you would use Compact width and Regular height when in Portrait and Compact height and Regular width when in Landscape.
It's my first try on IOS animation, so if I'm worry from the very beginning, just tell me the right direction.
All I want: when I click ButtonOne, Label disappears slowly.
The code as below:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var labelHeight: NSLayoutConstraint!
private var isHidden: Bool = false
#IBAction func clickButtonOne(sender: UIButton) {
isHidden = !isHidden
if isHidden {
labelHeight.constant = 0
} else {
labelHeight.constant = 60
}
UIView.animateWithDuration(1.0, animations: {
() -> Void in
self.view.layoutIfNeeded()
}, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
Before I click ButtonOne:
After I click ButtonOne(label shrinks from bottom to top):
The UILabel is disappearing, but it's content is still visible.
You need to set the clipsToBounds property of the UILabel to true.
label.clipsToBounds = true
You can set the same property in the interface builder by checking the Clip Subviews property in the attributes inspector.
I think you should also animate UIView.alpha property:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var button: UIButton!
#IBOutlet weak var labelHeight: NSLayoutConstraint!
private var isHidden: Bool = false
#IBAction func clickButtonOne(sender: UIButton) {
isHidden = !isHidden
var alpha: CGFloat = 1
if isHidden {
alpha = 0
labelHeight.constant = 0
} else {
labelHeight.constant = 60
}
UIView.animateWithDuration(1.0, animations: {
() -> Void in
self.button.alpha = alpha
self.view.layoutIfNeeded()
}, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
import UIKit
class PageViewController: UIViewController {
#IBOutlet weak var myScrView: UIScrollView!
#IBOutlet weak var pagectr: UIPageControl!
#IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
myScrView.tag = 1
myScrView.autoresizingMask = UIViewAutoresizing.None
self.view.addSubview(myScrView)
self.setupScrollView(myScrView)
pagectr.tag = 12
pagectr.numberOfPages = 9
pagectr.autoresizingMask = UIViewAutoresizing.None
self.view.addSubview(pagectr)
}
func setupScrollView(scrMain:UIScrollView) -> Void {
var imgesArray : NSMutableArray = []
for position in 1...9 {
var strImage : String = "\(position).jpeg"
var imges = UIImage(named: strImage)
imgesArray.addObject(imges!)
imageView.contentMode = UIViewContentMode.ScaleToFill
imageView.image = imges
imageView.tag = position+1
scrMain.addSubview(imageView)
println(imageView)
}
scrMain.contentSize = CGSizeMake(scrMain.frame.size.width*10, scrMain.frame.size.height)
NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "scrollingTimer", userInfo:nil, repeats: true)
}
func scrollingTimer(){
let scrMain: UIScrollView = self.view.viewWithTag(1) as UIScrollView
let pgctr: UIPageControl = self.view.viewWithTag(12) as UIPageControl
let contentOffset = scrMain.contentOffset.x as CGFloat
var nextPage = (CGFloat)(contentOffset/scrMain.frame.size.width) + 1
if(nextPage != 9){
scrMain.scrollRectToVisible(CGRectMake(nextPage*scrMain.frame.size.width, 0, scrMain.frame.size.width, scrMain.frame.size.height), animated: true)
pgctr.currentPage = Int(nextPage)
}
else{
scrMain.scrollRectToVisible(CGRectMake(0, 0, scrMain.frame.size.width, scrMain.frame.size.height), animated: true)
pgctr.currentPage = 1
}
}
}
I want to make a image slide show app using swift in ios please help me it's show only one image.I get a blank screen, almost as if the animations aren't keeping up, and then when I wait a moment and swipe again the image views speed up into place and works normally again. Any idea what I'm doing wrong? What is the best practice when it comes to implementing an image carousel like this with a dynamic amount of images (here they're hardcoded)?