Change UIScrollView Content size - ios

I have ViewController with UIScrollView, some UIImages and UIButtons.
In the Storyboard I set the size of UIScrollView to: width: 320, height: 570
I want to change Contentsize of my UIScrollView when the ViewController was loaded.
I added side in the viewDidLoad:
scrlMain.contentSize = CGSize(width: 320,height: 790)
And also I added code in the viewDidLayoutSubviews:
self.scrlMain.translatesAutoresizingMaskIntoConstraints = true
But my UIScrollView is still the last size = 570.
I can't use viewDidAppear because, when I press the button, it need it to change color. When it has changed color, my UIScrollView moves to up.
What did I do wrong?
All code:
override func viewDidLoad() {
super.viewDidLoad()
scrlMain.delegate = self
scrlMain.contentSize = CGSizeMake(320, 790)
}
override func viewDidLayoutSubviews() {
self.scrlMain.translatesAutoresizingMaskIntoConstraints = true
self.scrlMain.contentSize = CGSize(width: self.scrlMain.frame.width, height: 60.0 + 5 * (self.scrlMain.frame.width / 16.0 * 5.0));
}

there was an error in the this function:
override func viewDidLayoutSubviews() {
self.scrlMain.translatesAutoresizingMaskIntoConstraints = true
self.scrlMain.contentSize = CGSize(width: self.scrlMain.frame.width, height: 60.0 + 5 * (self.scrlMain.frame.width / 16.0 * 5.0));
}
I delete this code:
self.scrlMain.contentSize = CGSize(width: self.scrlMain.frame.width, height: 60.0 + 5 * (self.scrlMain.frame.width / 16.0 * 5.0));
And all was right

Hey #Dim you can try this-
yourScrollView.contentSize = CGSizeMake(320, 568)
And you can change size 568 to whatever you want.

Try this:
yourScrollView.userInteractionEnabled = YES
and you please maintain the difference between your screen size and your scrollview content size... so that it can be visible properly
suppose yourScrollViewSize greatertThan yourScreenSize

override func viewDidLayoutSubviews() {
DispatchQueue.main.async {
self.scrollview.translatesAutoresizingMaskIntoConstraints = true
self.scrollview.contentSize = CGSize(width:0, height:self.scrollview.frame.height*2) // whatever hight you want
}
}

It is also possible to change the content size from within the page without running ViewDidLoad again.
Just add
scrollView.layoutIfNeeded()
after you set the new contentSize
Example when you change the content size (viewImages) within the UIscrollView (scrollViewImages)
viewImages.frame.size = CGSize(width: width, height: 128)
viewImages.translatesAutoresizingMaskIntoConstraints = true
viewImages.setNeedsLayout()
scrollViewImages.setNeedsLayout()
scrollViewImages.layoutIfNeeded()

Related

UIImageView under UIScrollview does not fit on top screen

I have place UIImageView under UIScrollView on screen with constant width same as screen, and it works fine in iphone 5s but on iphone 7 or 8 the size of image is less than the width of screen size as shared on screenshots.
here is my code:
let x = CGFloat(selectedEvent.album?.count ?? 0)
pageControl.numberOfPages = (selectedEvent.album?.count ?? 0)
for index in 0..<(selectedEvent.album?.count ?? 0) {
frame.origin.x = scroll.frame.size.width * CGFloat(index)
frame.size = scroll.frame.size
print(self.frame.size.width)
print(scroll.frame.size.width)
print(frame.size.width)
let image = UIImageView(frame: frame)
image.contentMode = .scaleToFill
print(image.frame.size.width)
if (selectedEvent.album?.count ?? 0) > 0 {
selectedEvent.getAlbumImage(key: selectedEvent.album![index], completion: { (gotImage:UIImage) in
image.image = gotImage
})
} else {
image.image = UIImage(named: "defaultImage.jpg")
}
scroll .addSubview(image)
}
self.scroll.contentSize = CGSize(width: scroll.frame.size.width * x, height: scroll.frame.size.height)
pageControl.addTarget(self, action: #selector(self.changePage(sender:)), for: UIControlEvents.valueChanged)
here is the Print Log
320.0
320.0
320.0
320.0
320.0
320.0
320.0
320.0
In shorts, views might not have updated frames on viewDidLoad or ViewWillAppear methods instead views are initialised with storyboard sizes. So you are not getting updated rect for iPhone 7 or other devices.
Another reason is scrollview adjusts it's subview automatically. So disable it on viewDidLoad().
override func viewDidLoad() {
super.viewDidLoad()
self.scroll.contentInsetAdjustmentBehavior = .never;
// write your code
}
You should add subviews on viewDidLoad() method as you have done already and update frame & scrollview content related changes on viewDidLayoutSubviews().
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews();
for view:UIView in self.scroll.subviews {
frame.origin.x = self.scroll.frame.size.width * CGFloat(self.scroll.subviews.index(of: view)!);
frame.size = scroll.frame.size
view.frame = frame;
}
self.scroll.contentSize = CGSize(width: scroll.frame.size.width * selectedEvent.album?.count , height: scroll.frame.size.height)
}
Hope will work.
You want the frame width to be the screen width. Use as :
let size = UIScreen.main.bounds.size
self.scroll.contentSize = CGSize(width: size.width, height: scroll.frame.size.height)

Change the height of UISegmented Control using IB?

How can i change the height of UISegmented control. I'm using Swift 3.0 with xcode 8. Height property is disabled by default.
I found this:
https://stackoverflow.com/a/41889155/7652057
#IBDesignable class MySegmentedControl: UISegmentedControl {
#IBInspectable var height: CGFloat = 29 {
didSet {
let centerSave = center
frame = CGRect(x: frame.minX, y: frame.minY, width: frame.width, height: height)
center = centerSave
}
}
}
https://stackoverflow.com/a/37716960/7652057
One of three options from the link,
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let rect = CGRect(origin: segment.frame.origin, size: CGSize(width: segment.frame.size.width, height: 100))
segment.frame = rect
}
Ok, I was trying to do it for a long while and here is the solution.
Firstly, It is possible within IB but for that we need to have a good bunch of autolayout constraints.
I've placed that Segmented control in a UIVIew with all the edges pinned inside it.
Then I gave the desired height to that view and it worked.
Also.. thanks to all of your answer
It's very easy. You can access it programmaticly by using frame's height:
yourSegmentedControllOutlet.frame.size.height = yourHeight

Custom UINavigationBar - Animating Intrinsic Height Changes

In this particular scenario, I'm actually very confused. I have subclassed UINavigationBar, noted Apple's outdated sample code, realized that sizeToFit is never called and overrode intrinsicContentSize and layoutSubviews to calculate the necessary height. Everything works well when it comes to calculating the height based on a custom view I provide (I use systemLayoutSizeFittingSize for calculating the height dynamically based on a custom content view/titleView).
The odd part is, when I attempt to animate any changes, I can animate changes in the custom titleView, but when reloading the intrinsicContentSize via invalidateIntrinsicContentSize(), the view frame changes do not animate. It snaps.
Sample code:
let delta = destinationTextFieldContainerView.frame.minX - originTextFieldContainerView.frame.minX + originTextFieldContainerView.frame.height
textContainersSeparatorConstraint.constant = -delta
UIView.animateWithDuration(2, delay: 2, options: UIViewAnimationOptions.CurveEaseIn, animations: {
self.customContainerNavigationBar.invalidateIntrinsicContentSize()
self.customContainerNavigationBar.layoutIfNeeded()
}) { (_) in
self.customContainerNavigationBar.invalidateIntrinsicContentSize()
}
The one constraint value change will animate, but unfortunately (because navBars don't rely on auto layout) it seems there's a problem updating the frame. I've attempted updating the frame directly before invalidating the intrinsic size with no success. I've also tried a height constraint, listing it in key frame animations with different timing offsets, invalidating the layout at different points in time, all to no success. Any help would be greatly appreciated.
Resizing code can be found here:
override func intrinsicContentSize() -> CGSize {
var navigationBarSize = super.intrinsicContentSize()
navigationBarSize.width = superview?.frame.width ?? 0
guard let titleView = navigationItem?.titleView else {
return navigationBarSize
}
let fittingSize = CGSize(width: navigationBarSize.width, height: UILayoutFittingCompressedSize.height)
let titleViewSize = titleView.systemLayoutSizeFittingSize(fittingSize)
navigationBarSize.height = max(titleViewSize.height, 44)
navigationBarSize.width = UIViewNoIntrinsicMetric
return navigationBarSize
}
override func layoutSubviews() {
super.layoutSubviews()
guard let navigationItem = navigationItem, titleView = navigationItem.titleView else {
return
}
var navigationBarSize = bounds.size
navigationBarSize.width = superview?.frame.width ?? 0
var fittingSize = CGSize(width: navigationBarSize.width, height: UILayoutFittingCompressedSize.height)
if let leftBarButtonItem = navigationItem.leftBarButtonItem, leftButtonCustomView = leftBarButtonItem.customView {
fittingSize.width -= leftButtonCustomView.frame.width + leftButtonCustomView.frame.origin.x + 22
}
let titleViewSize = titleView.systemLayoutSizeFittingSize(fittingSize, withHorizontalFittingPriority: UILayoutPriorityRequired, verticalFittingPriority: UILayoutPriorityDefaultLow)
titleView.frame = CGRect(origin: CGPoint(x: titleView.frame.origin.x, y: 0), size: titleViewSize)
titleView.setNeedsLayout()
titleView.layoutIfNeeded()
if let leftBarButtonItem = navigationItem.leftBarButtonItem, leftButtonCustomView = leftBarButtonItem.customView {
var customViewFrame = CGRect(origin: CGPoint.zero, size: navigationBarSize)
let customViewSize = leftButtonCustomView.systemLayoutSizeFittingSize(customViewFrame.size, withHorizontalFittingPriority: UILayoutPriorityDefaultLow, verticalFittingPriority: UILayoutPriorityDefaultLow)
customViewFrame.size = customViewSize
leftButtonCustomView.frame = customViewFrame
leftButtonCustomView.setNeedsLayout()
leftButtonCustomView.layoutIfNeeded()
}
invalidateIntrinsicContentSize()
}

Swift - Add UIImageView as subview of UIWebView scrollView and scaling

I have a UIWebView and I have successfully added a UIImage view to the UIWebView’s scrollView like so:
let localUrl = String(format:"%#/%#", PDFFilePath, fileNameGroup)
let url = NSURL.fileURLWithPath(localUrl)
panRecognizer = UITapGestureRecognizer(target: self, action: #selector(panDetected))
pinchRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(pinchDetected))
panRecognizer.delegate = self
pinchRecognizer.delegate = self
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)
webview.loadRequest(NSURLRequest(URL:url))
webview.gestureRecognizers = [pinchRecognizer, panRecognizer]
let stampView:StampAnnotation = StampAnnotation(imageIcon: UIImage(named: "approved.png"), location: CGPointMake(currentPoint.x, currentPoint.y))
self.webview.scrollView.addSubview(stampView)
My UIWebView scrollView is scalable. Now I am looking for away to have my UIImageView (StampAnnotation is a class and UIImageView is its subclass) scale when the scrollView scales. So if the user zooms in on the scrollView, the UIImageView will get bigger and stay in a fixed position and if the user zooms out, the UIImageView will get smaller while the scrollView gets smaller while staying in a fixed position.
I really hope that makes sense. I have tried the following:
func pinchDetected(recognizer:UIPinchGestureRecognizer)
{
for views in webview.scrollView.subviews
{
if(views.isKindOfClass(UIImageView))
{
views.transform = CGAffineTransformScale(views.transform, recognizer.scale, recognizer.scale)
recognizer.scale = 1
}
}
if(appDelegate.annotationSelected == 0)
{
webview.scalesPageToFit = true
}
else
{
webview.scalesPageToFit = false
}
}
but this does nothing, if I remove this line:
recognizer.scale = 1
it scales way too big too fast. My question is, how do I get my UIImageView to scale when the UIWebview’s scrollView scrolls?
Any help would be appreciated.
This solved my problem.
func scrollViewDidZoom(scrollView: UIScrollView) {
for views in webview.scrollView.subviews
{
if(views.isKindOfClass(UIImageView))
{
views.transform = CGAffineTransformMakeScale(scrollView.zoomScale, scrollView.zoomScale)
}
}
}
No it does not stay in a fixed position on the page, but I think that is a constraints issue?
You were close...
1) Add a property to hold onto an external reference for your stampViewFrame:
var stampViewFrame = CGRect(x: 100, y: 100, width: 100, height: 100)
2) Replace your scrollViewDidZoom() with this:
func scrollViewDidZoom(scrollView: UIScrollView) {
for views in webView.scrollView.subviews
{
if(views.isKindOfClass(UIImageView))
{
views.frame = CGRect(x: stampViewFrame.origin.x * scrollView.zoomScale, y: stampViewFrame.origin.y * scrollView.zoomScale, width: stampViewFrame.width * scrollView.zoomScale, height: stampViewFrame.height * scrollView.zoomScale)
}
}
}
3) Finally, because the zoom scale resets to 1 at the begining of each new zooming action, you need to adjust the value of your stampViewFrame property:
func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
stampViewFrame = CGRect(x: stampViewFrame.origin.x * scale, y: stampViewFrame.origin.y * scale, width: stampViewFrame.width * scale, height: stampViewFrame.height * scale)
}
I also tried to answer your other question about layout during orientation change, but I now have a much better understanding of what you are trying to do. If you want your stampView to always be on in the same place relative to the web content, you have to get into HTML/JS because the webpage lays itself out dynamically. A much much more simple (and hopefully close enough) solution would be to add the following:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
webView.frame = view.bounds
stampView.frame = stampViewFrame
}
Use the scroll delegate method of scrollViewDidZoom :
func scrollViewDidZoom(scrollView: UIScrollView){
//Change the subview of scroll frame as per the scroll frame scale
//rect = initial position & size of the image.<class instance>
stampView.frame = CGRectMake((CGRectGetMaxX(rect)-rect.size.width)*webView.scrollView.zoomScale, (CGRectGetMaxY(rect)-rect.size.height)*webView.scrollView.zoomScale, rect.width*webView.scrollView.zoomScale,rect.height*webView.scrollView.zoomScale)
}

How do I change UIView Size?

I have trouble with modifying my UIView height at launch.
I have to UIView and I want one to be screen size * 70 and the other to fill the gap.
here is what I have
#IBOutlet weak var questionFrame: UIView!
#IBOutlet weak var answerFrame: UIView!
let screenSize:CGRect = UIScreen.mainScreen().bounds
and
questionFrame.frame.size.height = screenSize.height * 0.70
answerFrame.frame.size.height = screenSize.height * 0.30
It has no effect on the app during run time.
I use autolayout but I only have margins constraints...
Am I doing it all wrong?
This can be achieved in various methods in Swift 3.0 Worked on Latest version MAY- 2019
Directly assign the Height & Width values for a view:
userView.frame.size.height = 0
userView.frame.size.width = 10
Assign the CGRect for the Frame
userView.frame = CGRect(x:0, y: 0, width:0, height:0)
Method Details:
CGRect(x: point of X, y: point of Y, width: Width of View, height:
Height of View)
Using an Extension method for CGRECT
Add following extension code in any swift file,
extension CGRect {
init(_ x:CGFloat, _ y:CGFloat, _ w:CGFloat, _ h:CGFloat) {
self.init(x:x, y:y, width:w, height:h)
}
}
Use the following code anywhere in your application for the view to set the size parameters
userView.frame = CGRect(1, 1, 20, 45)
Here you go. this should work.
questionFrame.frame = CGRectMake(0 , 0, self.view.frame.width, self.view.frame.height * 0.7)
answerFrame.frame = CGRectMake(0 , self.view.frame.height * 0.7, self.view.frame.width, self.view.frame.height * 0.3)
Swift 3 and Swift 4:
myView.frame = CGRect(x: 0, y: 0, width: 0, height: 0)
Hi create this extends if you want. Update 2021 Swift 5
Create File Extends.Swift and add this code (add import foundation where you want change height)
extension UIView {
var x: CGFloat {
get {
self.frame.origin.x
}
set {
self.frame.origin.x = newValue
}
}
var y: CGFloat {
get {
self.frame.origin.y
}
set {
self.frame.origin.y = newValue
}
}
var height: CGFloat {
get {
self.frame.size.height
}
set {
self.frame.size.height = newValue
}
}
var width: CGFloat {
get {
self.frame.size.width
}
set {
self.frame.size.width = newValue
}
}
}
For Use (inherits Of UIView)
inheritsOfUIView.height = 100
button.height = 100
print(view.height)
For a progress bar kind of thing, in Swift 4
I follow these steps:
I create a UIView outlet : #IBOutlet var progressBar: UIView!
Then a property to increase its width value after a user action var progressBarWidth: Int = your value
Then for the increase/decrease of the progress progressBar.frame.size.width = CGFloat(progressBarWidth)
And finally in the IBACtion method I add progressBarWidth += your value for auto increase the width every time user touches a button.
You can do this in Interface Builder:
1) Control-drag from a frame view (e.g. questionFrame) to main View, in the pop-up select "Equal heights".
2)Then go to size inspector of the frame, click edit "Equal height to Superview" constraint, set the multiplier to 0.7 and hit return.
You'll see that constraint has changed from "Equal height to..." to "Proportional height to...".
Assigning questionFrame.frame.size.height= screenSize.height * 0.30 will not reflect anything in the view. because it is a get-only property. If you want to change the frame of questionFrame you can use the below code.
questionFrame.frame = CGRect(x: 0, y: 0, width: 0, height: screenSize.height * 0.70)
I know that there is already a solution to this question, but I found an alternative to this issue and maybe it could help someone.
I was having trouble with setting the frame of my sub view because certain values were referring to its position within the main view. So if you don't want to update your frame by changing the whole frame via CGRect, you can simply change a value of the frame and then update it.
// keep reference to you frames
var questionView = questionFrame.frame
var answerView = answerFrame.frame
// update the values of the copy
questionView.size.height = CGFloat(screenSize.height * 0.70)
answerView.size.height = CGFloat(screenSize.height * 0.30)
// set the frames to the new frames
questionFrame.frame = questionView
answerFrame.frame = answerView

Resources