Maintain contentOffset of UITextView on orientation change - ios

Is it possible to change the content offset of a UITextView so when the user moves from portrait to landscape (or vice versa), the text which is visible to them remains the same?
So if the user was at (in portrait mode)
....some text....
....some text2....
....I'm here.... //this is the visible area
....more text....
moves to landscape, it should be
....some text....some text2....
....I'm here....more text.... //this is the visible area
.....
The UITextView is non-editable but scrollable.

Here you have a short, self contained, compilable example :
import UIKit
class ViewController: UIViewController {
var textView: UITextView!
var percentOfScroll:CGFloat = 0
override func viewDidLoad() {
self.textView = UITextView(frame: CGRectZero)
self.textView.layer.borderColor = UIColor.blackColor().CGColor
self.textView.layer.borderWidth = 1
self.textView.editable = false
self.textView.text = "Lorem ipsum... some longish text"
self.view.addSubview(self.textView)
let leftConstraint = NSLayoutConstraint(item: self.textView, attribute: .Leading, relatedBy: .Equal, toItem: self.view, attribute: .Leading, multiplier: 1, constant: 10)
let rightConstraint = NSLayoutConstraint(item: self.textView, attribute: .Trailing, relatedBy: .Equal, toItem: self.view, attribute: .Trailing, multiplier: 1, constant: -10)
let topConstraint = NSLayoutConstraint(item: self.textView, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1, constant: 44)
let centerConstraint = NSLayoutConstraint(item: self.textView, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 1, constant: 0)
self.textView.translatesAutoresizingMaskIntoConstraints = false
self.view.addConstraints([leftConstraint, rightConstraint, topConstraint, centerConstraint])
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let contentSize = self.textView.contentSize
let newOffset = contentSize.height * percentOfScroll
self.textView.contentOffset = CGPoint(x: 0, y: newOffset)
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
let contentSize = self.textView.contentSize
let contentOffset = self.textView.contentOffset
self.percentOfScroll = contentOffset.y / contentSize.height
}
}
The idea is to get the amount of scrolled content in relation to its height before rotation (viewWillTransitionToSize) and using it calculate new contentOffset after (viewDidLayoutSubviews is also called after size change).
Bear in mind that this doesn't give a 100% precise result, but I haven't been able to come up with anything better , and maybe this will be enough for you.

Related

Tab Bar overlap view behind

I can't seem to fix the issue about this where I adjusted the Tab Bar height to 60 from viewWillLayoutSubviews() but the overlay view doesn't seem to acknowledge the adjusted height and follow suit.
Other similar questions I found are not actually alike (see here: iOS 7 Custom TableView Is Under TabBar) as their Tab Bar is translucent, and mine's not.
Here is what I implemented so far:
In my custom UITabBarController:
override func viewWillLayoutSubviews() {
var newTabBarFrame = tabBar.frame
let newTabBarHeight: CGFloat = 60
newTabBarFrame.size.height = newTabBarHeight
newTabBarFrame.origin.y = self.view.frame.size.height - newTabBarHeight
tabBar.frame = newTabBarFrame
}
In one of my tab's UIViewController:
override func viewDidLoad() {
view.addSubview(tableView)
NSLayoutConstraint.activate([
NSLayoutConstraint(item: tableView, attribute: NSLayoutAttribute.leading, relatedBy: .equal, toItem: view, attribute: NSLayoutAttribute.leading, multiplier: 1, constant: 0),
NSLayoutConstraint( item: tableView, attribute: NSLayoutAttribute.top, relatedBy: .equal, toItem: view, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0),
NSLayoutConstraint(item: tableView, attribute: NSLayoutAttribute.trailing, relatedBy: .equal, toItem: view, attribute: NSLayoutAttribute.trailing, multiplier: 1, constant: 0),
NSLayoutConstraint(item: tableView, attribute: NSLayoutAttribute.bottom, relatedBy: .equal, toItem: view, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0)
])
}
This is the current result:
You can see the overlay view is partially blocked. This happens on all other tab's overlay view controller
BTW, I already make sure the tableview's translatesAutoresizingMaskIntoConstraints is set to false
You can use a custom UITabBar to do this. Just override sizeThatFits(_:) to use your custom height:
class TabBar: UITabBar {
private let height:CGFloat = 60
override func sizeThatFits(_ size: CGSize) -> CGSize {
var bottomSafeAreaInsets: CGFloat = 0
if #available(iOS 11.0, *) {
bottomSafeAreaInsets = UIApplication.shared.keyWindow?.safeAreaInsets.bottom ?? 0
}
return CGSize(width: size.width, height: height + bottomSafeAreaInsets)
}
}

IOS how to completely remove a View

I want to hide a view completely. I am new to ios. But I have great working experience in android.
So in android We can set visibility to gone. and it completely removes the view from layout. Same I want to do in IOS. here is the layout/design example
View 1
View 2 ( it is the one I want to hide and show)
View 3
now when I want to hide the view 2 I want the space of view 2 also vanish from screen and View 1 and View 3 must stick together . and when view 2 is set to visible then it must display in sequence. i.e View 1,2,3
Right now what I am doing is setting view2.ishidden = true but its not working in the way I want.
Please tell me what is equivalent to view.gone of android in IOS. ???
There are a few ways in achieving this but what you are missing here is some key information on how your layout is being set.
I will assume that the 3 views you are having are vertically aligned, are one next to each other and have equal width.
Programmatically what we are looking at from horizontal perspective this is done:
let firstLeading = NSLayoutConstraint(item: view1, attribute: .leading, relatedBy: .equal, toItem: parent, attribute: .leading, multiplier: 1.0, constant: 0.0)
let betweenSecondAndFirst = NSLayoutConstraint(item: view2, attribute: .leading, relatedBy: .equal, toItem: view1, attribute: .trailing, multiplier: 1.0, constant: 0.0)
let secondEqualWidth = NSLayoutConstraint(item: view2, attribute: .width, relatedBy: .equal, toItem: view1, attribute: .width, multiplier: 1.0, constant: 0.0)
let betweenThirdAndSecond = NSLayoutConstraint(item: view3, attribute: .leading, relatedBy: .equal, toItem: view2, attribute: .trailing, multiplier: 1.0, constant: 0.0)
let lastEqualWidth = NSLayoutConstraint(item: view3, attribute: .width, relatedBy: .equal, toItem: view1, attribute: .width, multiplier: 1.0, constant: 0.0) // Note to view1 to make things easier
let lastTrailing = NSLayoutConstraint(item: view3, attribute: .trailing, relatedBy: .equal, toItem: parent, attribute: .trailing, multiplier: 1.0, constant: 0.0)
And when the second is being skipped we may simply disable betweenThirdAndSecond and add betweenThirdAndFirst as:
let betweenThirdAndFirst = NSLayoutConstraint(item: view3, attribute: .leading, relatedBy: .equal, toItem: view1, attribute: .trailing, multiplier: 1.0, constant: 0.0)
You can play with properties on constraints to enable or disable them. Or you can simply use priorities and toggle them for instance from 900 to 100. You can actually setup all of these constraints in storyboard and then drag the 2 as outlets into your code. Then simply have:
func setMiddleViewShown(_ shown: Bool) {
UIView.animate(withDuration: 0.3) {
self.betweenThirdAndSecond.priority = UILayoutPriority(rawValue: shown ? 900.0 : 100.0)
self.betweenThirdAndFirst.priority = UILayoutPriority(rawValue: shown ? 100.0 : 900.0)
self.view2.alpha = shown ? 1.0 : 0.0
parent.layoutIfNeeded() // parent is most likely "self.view"
}
}
This way is probably best from what you can control (mostly animations). But you may as well use UIStackView which has methods to insert or remove views. UICollectionView should work as well. Or you know.. just do it all programmatically, ignore constraints and simply set frame for each of the views.
A minimum I can think of in using UIStackView is the following and it works:
class ViewController: UIViewController {
let views: [UIView] = [
{ let view = UIView(); view.backgroundColor = .red; return view; }(),
{ let view = UIView(); view.backgroundColor = .green; return view; }(),
{ let view = UIView(); view.backgroundColor = .blue; return view; }()
]
lazy var stackView: UIStackView = {
let stackView = UIStackView(frame: CGRect(x: 50.0, y: 100.0, width: 300.0, height: 200.0))
self.view.addSubview(stackView)
stackView.backgroundColor = .black
stackView.distribution = .fillEqually
return stackView
}()
override func viewDidLoad() {
super.viewDidLoad()
stackView.addArrangedSubview(views[0])
stackView.addArrangedSubview(views[1])
stackView.addArrangedSubview(views[2])
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
UIView.animate(withDuration: 0.3) {
if self.stackView.arrangedSubviews.count == 3 {
self.views[1].alpha = 0.0
self.stackView.removeArrangedSubview(self.views[1])
} else {
self.views[1].alpha = 1.0
self.stackView.insertArrangedSubview(self.views[1], at: 1)
}
self.stackView.layoutIfNeeded()
}
}
}

How to make a view scroll against a scrollview animation?

So I have a UIView and I want to have it animate a translation in the opposite direction of the scrollviews scroll animation. How would I go about doing this? Of course this should be depend on the scrollview.contentOffset I think anyway. So if you scroll the other way it goes back to it's place. So the translation is dependent on how far the user scrolls. I am trying to use the following code. Also note that the UIView I currently do not have as a child of the scrollview. It is suppose to stay on screen at all time, but change positions.
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.x >= scrollView.contentSize.width {
UIView.animate(withDuration: 2.0, animations: {
self.view.layoutIfNeeded()
})
}
A simple solution would be:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let percentage = scrollView.contentOffset.x / scrollView.contentSize.width
self.box.frame.origin.x = UIScreen.main.bounds.width * percentage
}
Just calculate the percentage of the contentSize that you have scrolled and set the X position to the same percentage of the screen width.
It could do with some improvements to make sure the view doesn't go beyond the bounds of the screen in certain conditions. So you may need to factor in the width of the box in the calculations as an enhancement.
Here is the code I used for testing, The background image is a 4K wallpaper image.
class ViewController: UIViewController {
var box = UIView()
var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
self.scrollView = UIScrollView()
self.scrollView.translatesAutoresizingMaskIntoConstraints = false
self.scrollView.delegate = self
self.view.addSubview(self.scrollView)
NSLayoutConstraint(item: scrollView, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: scrollView, attribute: .left, relatedBy: .equal, toItem: self.view, attribute: .left, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: scrollView, attribute: .right, relatedBy: .equal, toItem: self.view, attribute: .right, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: scrollView, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1.0, constant: 0).isActive = true
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.image = UIImage(named: "background")
self.scrollView.addSubview(imageView)
NSLayoutConstraint(item: imageView, attribute: .top, relatedBy: .equal, toItem: scrollView, attribute: .top, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: imageView, attribute: .left, relatedBy: .equal, toItem: scrollView, attribute: .left, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: imageView, attribute: .right, relatedBy: .equal, toItem: scrollView, attribute: .right, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: imageView, attribute: .bottom, relatedBy: .equal, toItem: scrollView, attribute: .bottom, multiplier: 1.0, constant: 0).isActive = true
box.frame = CGRect(x: 0, y: UIScreen.main.bounds.height - 110, width: 100, height: 100)
box.backgroundColor = .black
self.view.addSubview(box)
}
}
extension ViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let percentage = scrollView.contentOffset.x / scrollView.contentSize.width
let xPosition = UIScreen.main.bounds.width * percentage
self.box.frame.origin.x = xPosition
}
}

Swift - Keep UIImageView in the same position on rotate

I have UIWebView and in its scrollView, I added a UIImageView like so:
self.webview.scrollView.addSubview(image)
my problem is when I rotate my device from portrait to landscape the UIImageView does not stay at the position I originally set it to on the scrollView, I understand the width and height of the screen change, I guess what I am trying to do it change the the position on my UIImageView so it appears it did not change.
I have this method in place:
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
var newScrollViewFrame = webview.scrollView.frame
var newFrame = webview.frame
newFrame.size.width = size.width
newFrame.size.height = size.height
newScrollViewFrame.size.width = size.width
newScrollViewFrame.size.height = size.height
webview.frame = newFrame
webview.scrollView.frame = newScrollViewFrame
}
The current code inside this method just resize the UIWebView and its scroll view, but not the UIImageViews in the scrollView
Any help would be appreciated.
Thanks,
I have tried the following:
for views in webview.scrollView.subviews
{
if(views.isKindOfClass(UIImageView))
{
views.transform = CGAffineTransformMakeRotation(CGFloat(M_PI)/2);
}
}
but this puts on UIImageView sideways on rotate
Here is how I am adding the webview to the view:
webview = UIWebView()
webview.frame = self.view.bounds
webview.scrollView.frame = webview.frame
webview.userInteractionEnabled = true
webview.scalesPageToFit = true
webview.becomeFirstResponder()
webview.delegate = self
webview.scrollView.delegate = self
self.view.addSubview(webview)
I have half solved my problem, but doing the following:
webview.translatesAutoresizingMaskIntoConstraints = false
let horizontalConstraint = NSLayoutConstraint(item: webview, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
view.addConstraint(horizontalConstraint)
let verticalConstraint = NSLayoutConstraint(item: webview, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
view.addConstraint(verticalConstraint)
let widthConstraint = NSLayoutConstraint(item: webview, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 0.1, constant: 500)
view.addConstraint(widthConstraint)
let heightConstraint = NSLayoutConstraint(item: webview, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 500)
view.addConstraint(heightConstraint)
However now, the UIWebView is not full width or height :( Sooooo close.
I also tried this, but the UIImageView do not remain in the same spot.
let left = NSLayoutConstraint(item: self.webView, attribute: .Left, relatedBy: .Equal, toItem: self.view, attribute: .Left, multiplier: 1, constant: 0)
let right = NSLayoutConstraint(item: self.webView, attribute: .Right, relatedBy: .Equal, toItem: self.view, attribute: .Right, multiplier: 1, constant: 0)
let top = NSLayoutConstraint(item: self.webView, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1, constant: 0)
let bottom = NSLayoutConstraint(item: self.webView, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 1, constant: 0)
NSLayoutConstraint.activateConstraints([top, bottom, left, right])
I have also tried adding constraints to the UIImageView
let stampView:StampAnnotation = StampAnnotation(imageIcon: UIImage(named: "approved.png"), location: CGPointMake(currentPoint.x, currentPoint.y))
self.webview.scrollView.addSubview(stampView)
let left = NSLayoutConstraint(item: stampView, attribute: .Left, relatedBy: .Equal, toItem: self.webview.scrollView, attribute: .Left, multiplier: 1, constant: 0)
let right = NSLayoutConstraint(item: stampView, attribute: .Right, relatedBy: .Equal, toItem: self.webview.scrollView, attribute: .Right, multiplier: 1, constant: 0)
let top = NSLayoutConstraint(item: stampView, attribute: .Top, relatedBy: .Equal, toItem: self.webview.scrollView, attribute: .Top, multiplier: 1, constant: 0)
let bottom = NSLayoutConstraint(item: stampView, attribute: .Bottom, relatedBy: .Equal, toItem: self.webview.scrollView, attribute: .Bottom, multiplier: 1, constant: 0)
NSLayoutConstraint.activateConstraints([top, bottom, left, right])
same result, UIImageView does not stay in the same spot.
UPDATE
My webview:
webview = UIWebView()
webview.userInteractionEnabled = true
webview.scalesPageToFit = true
webview.becomeFirstResponder()
webview.delegate = self
webview.scrollView.delegate = self
self.view.addSubview(webview)
webview.loadRequest(NSURLRequest(URL:url))
webview.gestureRecognizers = [pinchRecognizer, panRecognizer]
webview.translatesAutoresizingMaskIntoConstraints = false
let left = NSLayoutConstraint(item: webview, attribute: .Left, relatedBy: .Equal, toItem: self.view, attribute: .Left, multiplier: 1, constant: 0)
let right = NSLayoutConstraint(item: webview, attribute: .Right, relatedBy: .Equal, toItem: self.view, attribute: .Right, multiplier: 1, constant: 0)
let top = NSLayoutConstraint(item: webview, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1, constant: 0)
let bottom = NSLayoutConstraint(item: webview, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 1, constant: 0)
NSLayoutConstraint.activateConstraints([top, bottom, left, right])
UIImageView
stampView.translatesAutoresizingMaskIntoConstraints = false
let left = NSLayoutConstraint(item: stampView, attribute: .Left, relatedBy: .Equal, toItem: self.webview.scrollView, attribute: .Left, multiplier: 1, constant: 100)
let right = NSLayoutConstraint(item: stampView, attribute: .Right, relatedBy: .Equal, toItem: self.webview.scrollView, attribute: .Right, multiplier: 1, constant: 0)
let top = NSLayoutConstraint(item: stampView, attribute: .Top, relatedBy: .Equal, toItem: self.webview.scrollView, attribute: .Top, multiplier: 1, constant: 100)
let bottom = NSLayoutConstraint(item: stampView, attribute: .Bottom, relatedBy: .Equal, toItem: self.webview.scrollView, attribute: .Bottom, multiplier: 1, constant: 0)
let width = NSLayoutConstraint(item: stampView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 0.1, constant: 150)
let height = NSLayoutConstraint(item: stampView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 73)
NSLayoutConstraint.activateConstraints([left, right, top, bottom, width, height])
I just need to figure out the math to have this device be at the position of touch. (in percentages ?)
I think these things are always easier to do without using autolayout. To do this, I recomend using viewDidLayoutSubviews(). Here is my code:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
webView.frame = view.bounds
let screen = UIScreen.mainScreen().fixedCoordinateSpace
//These values will give a rect half the size of the screen and centered.
let width = screen.bounds.width / 2
let height = screen.bounds.height / 2
let x = (screen.bounds.width - width) / 2
let y = (screen.bounds.height - height) / 2
let absoluteRect = CGRect(x: x, y: y, width: width, height: height)
let stampRect = screen.convertRect(absoluteRect, toCoordinateSpace: webView)
stampView.frame = stampRect
//Change the orientation of the image
switch UIDevice.currentDevice().orientation {
case .LandscapeLeft:
stampView.image = UIImage(CGImage:originalImage.CGImage!, scale:originalImage.scale, orientation: UIImageOrientation.Left)
break
case .LandscapeRight:
stampView.image = UIImage(CGImage:originalImage.CGImage!, scale:originalImage.scale, orientation: UIImageOrientation.Right)
break
default:
stampView.image = UIImage(CGImage:originalImage.CGImage!, scale:originalImage.scale, orientation: UIImageOrientation.Up)
break
}
}
I am doing several things here...First I set the webViewFrame. Next, it is helpful here to define an absolute coordinate system relative to your screen. When the phone orientation changes, the values of screen will not change (allowing you to keep your imageView in the same place.) Next I define the desired frame for the stampView, then convert the absolute frame into its equivalent inside your scrollView (it's superView) and assign it to the stampView. Finally, if you want the image in your stampView to always be oriented correctly, you need to change the image orientation. CGAffineTransformMakeRotation only works if your view is square, but we can make it more general by actually changing the imageOrientation within the stampView. This requires a property for the original image:
let originalImage = UIImage(named: "image_name")!
Finally, because viewWillLayoutSubViews() is not called for landscape to landscape transitions, do the following:
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
view.setNeedsLayout()
}
This code doesn't make for the prettiest transitions, it should help with your layout problems.
To make the UIImageView keep the same size and stay in the same position relative to the UIWebView, you can set your views to be a percentage of their respective superView. Here I've created some mock views that illustrate the basic idea:
import UIKit
class ViewController: UIViewController {
//we create some views for testing and create references to the size and points we need for positioning
let webView = UIWebView()
let image = UIImageView()
let image2 = UIImageView()
var imageViewSize = CGSize()
var imageViewCenter = CGPoint()
override func viewDidLoad() {
super.viewDidLoad()
//set webView frame
webView.frame = self.view.bounds
webView.backgroundColor = UIColor.clearColor()
webView.userInteractionEnabled = true
webView.scalesPageToFit = true
webView.opaque = false
self.view.addSubview(webView)
//we will hold onto the original size of the UIImageView for later
imageViewSize = CGSizeMake(webView.bounds.size.width * 0.2, webView.bounds.size.height * 0.1)
//mock UIImageView
image.backgroundColor = UIColor.orangeColor()
image.frame.size = CGSizeMake(imageViewSize.width, imageViewSize.height)
image.center = CGPointMake(webView.bounds.size.width / 2, webView.bounds.size.height / 2)
webView.scrollView.addSubview(image)
//I've created a subset image to illustrate the orientation
image2.backgroundColor = UIColor.whiteColor()
image2.frame = CGRectMake(10, 10, 10, 10)
image.addSubview(image2)
}
And then change the frame when rotated (Notice that the position on the UIImageView and the width of the UIWebView are set relative to the height of their superViews and vice versa since the device is rotated):
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
image.frame.size = CGSizeMake(imageViewSize.width, imageViewSize.height)
image.center = CGPointMake(webView.bounds.size.height / 2, webView.bounds.size.width / 2)
webView.frame = CGRectMake(0, 0, self.view.bounds.size.height, self.view.bounds.size.width)
webView.scrollView.contentSize = webView.frame.size
}
}
Since you are creating the position and sizes of your views as percentages of their superViews, the code will play nicer with different device sizes (i.e. iPhone/iPad).

Move a View into Another view on button click in Swift iOS

I am stumbled upon an issue in an application that i am making. I need to place one view into another view programmatically on button click.
Now i need to move View 1 to the centre of View 2 on a button click with an animation. I tried to reposition the View1 to View 2 but i am not able to do it properly.
This is the Final result that i am trying to achieve.
CODE FOR CREATING THE RED VIEW
My.cellSnapshot = snapshopOfCell(cell)
var center = cell.center
My.cellSnapshot!.center = center
My.cellSnapshot!.alpha = 0.0
ingredientsTableView.addSubview(My.cellSnapshot!)
func snapshopOfCell(inputView: UIView) -> UIView {
UIGraphicsBeginImageContextWithOptions(inputView.bounds.size, false, 0.0)
inputView.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext() as UIImage
UIGraphicsEndImageContext()
let cellSnapshot : UIView = UIImageView(image: image)
cellSnapshot.layer.masksToBounds = false
cellSnapshot.layer.cornerRadius = 0.0
cellSnapshot.layer.shadowOffset = CGSizeMake(-5.0, 0.0)
cellSnapshot.layer.shadowRadius = 5.0
cellSnapshot.layer.shadowOpacity = 0.4
return cellSnapshot
}
Please help me in solving the problem.
Thanks in advance
You can move the view for 0.5 seconds.
UIView.animateWithDuration(0.5, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
redView.center = greenView.center
}, completion: nil)
i created a sample project and set up a target view as well as a button to start the animation in storyboard like this:
then in code i added the view to move and the button target code like this:
var sourceView: UIView!
#IBOutlet weak var destinationView: UIView!
var sourceViewPositioningConstraints = [NSLayoutConstraint]()
override func viewDidLoad() {
super.viewDidLoad()
sourceView = UIView()
sourceView?.backgroundColor = UIColor.redColor()
sourceView?.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(sourceView)
// size constraints
NSLayoutConstraint(item: sourceView, attribute: .Width, relatedBy: .Equal, toItem: view, attribute: .Width, multiplier: 0.25, constant: 0).active = true
NSLayoutConstraint(item: sourceView, attribute: .Width, relatedBy: .Equal, toItem: sourceView, attribute: .Height, multiplier: 16/9, constant: 0).active = true
// positioning constraints
sourceViewPositioningConstraints += [NSLayoutConstraint(item: sourceView, attribute: .Top, relatedBy: .Equal, toItem: topLayoutGuide, attribute: .BottomMargin, multiplier: 1, constant: 0)]
sourceViewPositioningConstraints += [NSLayoutConstraint(item: sourceView, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: 0)]
NSLayoutConstraint.activateConstraints(sourceViewPositioningConstraints)
}
#IBAction func move(sender: UIButton) {
// deactivate current positioning constraints
NSLayoutConstraint.deactivateConstraints(sourceViewPositioningConstraints)
sourceViewPositioningConstraints.removeAll()
// add new positioning constraints
sourceViewPositioningConstraints += [NSLayoutConstraint(item: sourceView, attribute: .CenterX, relatedBy: .Equal, toItem: destinationView, attribute: .CenterX, multiplier: 1, constant: 0)]
sourceViewPositioningConstraints += [NSLayoutConstraint(item: sourceView, attribute: .CenterY, relatedBy: .Equal, toItem: destinationView, attribute: .CenterY, multiplier: 1, constant: 0)]
NSLayoutConstraint.activateConstraints(sourceViewPositioningConstraints)
// animate constraint changes
UIView.animateWithDuration(1) {
self.view.layoutIfNeeded()
}
}
if you are not using autolayout for your movable view you can simply use something like this:
override func viewDidLoad() {
super.viewDidLoad()
sourceView = UIView()
sourceView?.backgroundColor = UIColor.redColor()
sourceView.frame = CGRect(x: 40, y: 40, width: 100, height: 100)
view.addSubview(sourceView)
}
#IBAction func move(sender: UIButton) {
// animate constraint changes
UIView.animateWithDuration(1) {
self.sourceView.center = self.destinationView.center
}
}

Resources