Circle Image View - ios

I am trying to make image view circled for profile pics.
It was working properly before I had put constrains of UiScreen width.
so here is the code
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var proPicH: NSLayoutConstraint! //Profile Picture Height
#IBOutlet weak var proPicW: NSLayoutConstraint! // Profile Picture Width
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
circleImage()
}
func circleImage() {
let screenSize = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
let width = screenWidth / 2
print("ScreenWidth: \(screenWidth)")
proPicW.constant = width
proPicH.constant = width
print("H:\(proPicH.constant)")
print("W:\(proPicW.constant)") //Here the height and width comes to my expectations
imageView.layer.cornerRadius = imageView.bounds.width / 2
imageView.clipsToBounds = true
print("Height: \(imageView.bounds.height)") // Here the height and width becomes more
}
}
Please help me with this to make image round

At the point in time where you set the image view corner radius its bounds haven't been updated to match the constraints yet. Change this line
imageView.layer.cornerRadius = imageView.bounds.width / 2
To
imageView.layer.cornerRadius = width / 2
So that the same value used to set the constraints is also used for the corner radius.
Note that if you update the constraints in some other piece of code you also new to update the corner radius to match.

I would suggest you to put
circleImage()
in viewDidAppears Methods

Use imageView.layer.cornerRadius = imageView.frame.size.width / 2
imageView.layer.maskToBounds=Yes;

Related

Swift ScrollView Layout Issue With PageController and Images iOS

I can't figure out how to set constraints for a scrollView with an imageView inside.
I am using the scrollView with a pageConroller to swipe thru a bunch of images.
See my layout in the picture below.
// Code for imageView
for index in 0..<drinksImagesArray.count {
frame.origin.x = scrollView.frame.size.width * CGFloat(index)
frame.size = scrollView.frame.size
let imageView = UIImageView(frame: frame)
imageView.contentMode = .scaleAspectFit
imageView.image = UIImage(named: imagesArray[index].name)
self.scrollView.addSubview(imageView)
}
scrollView.contentSize = CGSize(width: scrollView.frame.size.width * CGFloat(imagesArray.count), height: scrollView.frame.size.height)
scrollView.delegate = self
Any suggestions? Thank you!
Layout
You will have much better luck using auto-layout --- it can handle all of the frame sizes and .contentSize for you.
Here's a quick example - it uses a view controller with a scroll view added in Storyboard, so it should be pretty easy for you to integrate with your code:
class ScrollingImagesViewController: UIViewController {
#IBOutlet var scrollView: UIScrollView!
var drinksImagesArray: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
// however you're populating your array...
drinksImagesArray = [
"drink1",
"drink2",
"drink3",
// etc...
]
// create a horizontal stack view
let stack = UIStackView()
stack.axis = .horizontal
stack.alignment = .fill
stack.distribution = .fillEqually
stack.spacing = 0
// add the stack view to the scroll view
stack.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(stack)
// use scroll view's contentLayoutGuide for content constraints
let svCLG = scrollView.contentLayoutGuide
NSLayoutConstraint.activate([
// stack view constrained Top / Bottom / Leading / Trailing of scroll view CONTENT guide
stack.topAnchor.constraint(equalTo: svCLG.topAnchor),
stack.bottomAnchor.constraint(equalTo: svCLG.bottomAnchor),
stack.leadingAnchor.constraint(equalTo: svCLG.leadingAnchor),
stack.trailingAnchor.constraint(equalTo: svCLG.trailingAnchor),
// stack view height == scroll view FRAME height
stack.heightAnchor.constraint(equalTo: scrollView.frameLayoutGuide.heightAnchor),
])
// create image views and add them to the stack view
drinksImagesArray.forEach { imgName in
let v = UIImageView()
v.backgroundColor = .lightGray
v.contentMode = .scaleAspectFit
// make sure we load a valid image
if let img = UIImage(named: imgName) {
v.image = img
}
stack.addArrangedSubview(v)
}
// stack distribution is set to .fillEqually, so we only need to set the
// width constraint on the first image view
// unwrap it
if let firstImageView = stack.arrangedSubviews.first {
firstImageView.widthAnchor.constraint(equalTo: scrollView.frameLayoutGuide.widthAnchor).isActive = true
}
}
}
Edit
After reviewing your Storyboard...
Auto-layout doesn't seem to like it when you add a UINavigationBar and a UIToolbar and a UIScrollView as subviews. In particular, it appears to confuse the scroll view's frame related constraints.
The fix is to first add constraints for your scroll view:
Top to Navigation Bar Bottom
Bottom to Page Control Top
Leading and Trailing to safe-area
Storyboard / Interface builder will complain that the scroll view is not configured properly. You can either ignore that, or select the scroll view and set Ambiguity to Never Verify:
Then, in your view controller class, we need to create a height constraint for the stack view we're adding to the scroll view, and set that height constant in viewDidLayoutSubviews().
Here's the full code:
//
// WasserhaushaltViewController.swift
// deSynthTheOceans
//
// Created by robinsonhus0 on 24.03.20.
// Copyright © 2020 robinsonhus0. All rights reserved.
//
import UIKit
import AVFoundation
import Charts
import FSCalendar
import HealthKit
struct WasserSpeicher: Codable {
let wassermenge: Double
let speicherdatum: String
let speicherStelle: Double
}
class WasserhaushaltViewController: UIViewController, UIScrollViewDelegate {
#IBOutlet weak var diagrammView: UIView!
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var pageControl: UIPageControl!
let drinksImagesArray = ["tapWater", "water", "milk", "cola", "coffee", "tea", "juice", "beer"]
var imageIndex = Int()
struct Drinks {
var name: String
var tagesMengeFactor: Double
var gesamtMengeFactor: Double
}
var frame = CGRect(x: 0, y: 0, width: 0, height: 0)
var pageNumber = CGFloat()
#IBOutlet weak var todaysWaterConsumptionLabel: UILabel!
#IBOutlet weak var waterGoalProgress: UIProgressView!
#IBOutlet weak var waterGoalLabel: UILabel!
#IBOutlet weak var wasserMengeStepper: UIStepper!
#IBOutlet weak var motivationTextView: UITextView!
#IBOutlet weak var wasserglasButton: UIBarButtonItem!
#IBOutlet weak var kleineFlascheButton: UIBarButtonItem!
#IBOutlet weak var grosseFlascheButton: UIBarButtonItem!
#IBOutlet weak var overAllWaterConsumptionLabel: UILabel!
// added
let scrollingImagesStackView = UIStackView()
var stackHeightConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
pageControl.numberOfPages = drinksImagesArray.count
setupDrinkImages()
}
func setupDrinkImages() {
// set stack view properties
scrollingImagesStackView.axis = .horizontal
scrollingImagesStackView.alignment = .fill
scrollingImagesStackView.distribution = .fillEqually
scrollingImagesStackView.spacing = 0
// add the stack view to the scroll view
scrollingImagesStackView.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(scrollingImagesStackView)
// use scroll view's contentLayoutGuide for content constraints
let svCLG = scrollView.contentLayoutGuide
NSLayoutConstraint.activate([
// stack view constrained Top / Bottom / Leading / Trailing of scroll view CONTENT guide
scrollingImagesStackView.topAnchor.constraint(equalTo: svCLG.topAnchor),
scrollingImagesStackView.bottomAnchor.constraint(equalTo: svCLG.bottomAnchor),
scrollingImagesStackView.leadingAnchor.constraint(equalTo: svCLG.leadingAnchor),
scrollingImagesStackView.trailingAnchor.constraint(equalTo: svCLG.trailingAnchor),
])
// create the stack view height constraint - it will be updated in viewDidLayoutSubviews
stackHeightConstraint = scrollingImagesStackView.heightAnchor.constraint(equalToConstant: 0)
stackHeightConstraint.isActive = true
// create image views and add them to the stack view
drinksImagesArray.forEach { imgName in
let v = UIImageView()
v.backgroundColor = .orange
v.contentMode = .scaleAspectFit
// make sure we load a valid image
if let img = UIImage(named: imgName) {
v.image = img
}
scrollingImagesStackView.addArrangedSubview(v)
}
// stack distribution is set to .fillEqually, so we only need to set the
// width constraint on the first image view
// unwrap it
if let firstImageView = scrollingImagesStackView.arrangedSubviews.first {
firstImageView.widthAnchor.constraint(equalTo: scrollView.frameLayoutGuide.widthAnchor).isActive = true
}
scrollView.delegate = self
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// since we have a UINavigationBar and a UIToolBar in the view hierarchy,
// we need to set this here
// Note: if the view size changes
// stack view height == scroll view FRAME height
stackHeightConstraint.constant = scrollView.frame.height
}
// func setupDrinkImages() {
// for index in 0..<drinksImagesArray.count {
// frame.origin.x = scrollView.frame.size.width * CGFloat(index)
// frame.size = scrollView.frame.size
//
// let imageView = UIImageView(frame: frame)
// imageView.contentMode = .scaleAspectFit
// imageView.image = UIImage(named: drinksImagesArray[index])
// self.scrollView.addSubview(imageView)
// }
// scrollView.contentSize = CGSize(width: scrollView.frame.size.width * CGFloat(drinksImagesArray.count), height: scrollView.frame.size.height)
// scrollView.delegate = self
// }
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
pageNumber = scrollView.contentOffset.x / scrollView.frame.size.width
pageControl.currentPage = Int(pageNumber)
}
}
Your (modified) Storyboard is too big to add here... if you have any trouble with the changes mentioned above, here it is: https://pastebin.com/2Q1uFUgL

How to set UIScrollView contensize when content is load asynchronously

My view hierarchy is this
PhotoDetailViewController.swift
View
UIScrollView
UIImageView
I set this up using storyboard, and add four constraints(top=0, bottom=0, leading=0, tailing=0) to UIScrollView, four constraints(top=0, bottom=0, leading=0, tailing=0) to UIImageView, but there are two error says
"ScrollView has ambiguous scrollable content width"
"ScrollView has ambiguous scrollable content height"
I understand that this is because I haven't set UIScrollView contentSize, but What I trying to do is load photo from PHAsset asynchronously, so I can only get the photo size at run time. So the question is:
1:Given that photo size can only be get at run time, how to solve the "ambiguous scrollable content" error?
2:In which View's life cycle method should I call PHImageManager.requestImageForAsset? because I think I should set UIScrollView contentSize programmatically, but when?
update with PhotoDetailViewController.swift
import UIKit
import Photos
class PhotoDetailViewController : UIViewController {
#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!
var devicePhotosAsset : PHFetchResult!
var index = 0
var photo : UIImage!
var imgManager:PHImageManager!
#IBOutlet weak var imageView : UIImageView!
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func awakeFromNib() {
self.imgManager = PHImageManager()
}
override func viewDidLoad() {
super.viewDidLoad()
self.displayPhoto()
}
override func viewWillLayoutSubviews() {
super.viewDidLayoutSubviews()
updateMinZoomScaleForSize()
updateConstraintsForSize()
}
func displayPhoto () {
_ = self.imgManager.requestImageForAsset(self.devicePhotosAsset[self.index] as! PHAsset, targetSize: PHImageManagerMaximumSize, contentMode: .AspectFit, options: nil, resultHandler: {(result, info) -> Void in
NSOperationQueue.mainQueue().addOperationWithBlock(){
self.imageView.image = result
}
})
}
private func targetSize() -> CGSize {
let scale = UIScreen.mainScreen().scale
let targetSize = CGSizeMake(CGRectGetWidth(self.imageView.bounds)*scale, CGRectGetHeight(self.imageView.bounds)*scale)
return targetSize
}
private func updateMinZoomScaleForSize() {
let size = scrollView.bounds.size
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
}
func recenterImage(){
let scrollViewSize = scrollView.bounds.size
let imageSize = imageView.frame.size
let horizontalSpace = imageSize.width < scrollViewSize.width ? (scrollViewSize.width - imageSize.width)/2 : 0
let verticalSpace = imageSize.height < scrollViewSize.height ? (scrollViewSize.height - imageSize.height)/2 : 0
scrollView.contentInset = UIEdgeInsets(top: verticalSpace, left: horizontalSpace, bottom: verticalSpace, right: horizontalSpace)
}
private func updateConstraintsForSize() {
let size = scrollView.bounds.size
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()
}
}
extension PhotoDetailViewController: UIScrollViewDelegate {
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return imageView
}
func scrollViewDidZoom(scrollView: UIScrollView) {
updateConstraintsForSize()
}
}
Your existing constraints are enough to set the content size, it's just that it's based on the image view intrinsic content size and that doesn't really exist until the image view has an image.
You can add a width and height constraint to the image view with default values and deactivate those constraints when the image is set to the view. Or you could use a placeholder image and avoid those extra constraints because you'd always have an intrinsic content size for the image view.
You should set two more constraint to your imageView.
Horizontally in Container (or you can say it center X)
Fixed Height
Second thing you can put UIView on Scrollview with Constraints like,
Top,leading,trailing,bottom,Horizontally in container(center x),fixed height).
Then add your imageview to that view. And can change it's constraint after getting image to resize it's height and width.
You can connect outlet of any constraint and can change it's constant programmatically.
Xcode UI builder has special type of constraint for such cases (when you can setup constraint only in runtime). It's so called "placeholder constraint" which will be removed at build time but helps to remove constraints errors for developing.
So solution is
Add some sample constraints IB and mark them as placeholders
Add needed constraints in runtime
When you get the data, just add these lines
float sizeOfContent = 0;
UIView *lLast = [yourscrollview.subviews lastObject];
NSInteger wd = lLast.frame.origin.y;
NSInteger ht = lLast.frame.size.height;
sizeOfContent = wd+ht;
yourscrollview.contentSize = CGSizeMake(yourscrollview.frame.size.width, sizeOfContent);
Hope this helps

horizontal scrollview for different screen sizes ios swift

Hi I need some help ScrollViews. I want to have a horizontal scrollview take up the bottom 25% of a screen and stay at 25% across all iPhone screen sizes. I am just not sure how to code it in Swift. I know that I should not give it a fixed width and height like I have. Does anyone know how I can do this or where I can look for help? My main problem is that when I switch between devices it does not stay the same height and width. I am using a stackview.
import UIKit
class paintedLadiesVC: UIViewController {
#IBOutlet weak var scrollView: UIScrollView!
let WIDTH: CGFloat = 414
let HEIGTH: CGFloat = 212
override func viewDidLoad() {
super.viewDidLoad()
for var x = 1; x <= 5; x++ {
let img = UIImage(named: "\(x)")
let imgView = UIImageView(image: img)
scrollView.addSubview(imgView)
imgView.frame = CGRectMake(-WIDTH + (WIDTH * CGFloat(x)), 1, WIDTH, HEIGTH)
}
scrollView.contentSize = CGSizeMake(WIDTH * 5, scrollView.frame.size.height)
}
}
Base your sizes on the device using 'UIDevice.currentDevice().width ' 'UIDevice.currentDevice().height'

How to constrain a UIImageView inside another view?

I have a universal iOS swift project in xcode, and am having trouble getting the sizes of a UIImageView right. The XIB structure is as follows:
View
|-- Card (View)
|-- CoverImage (UIImageView)
View is loaded into a UIScrollView by ViewController.swift. Card has top, bottom, trailing, and leading constraints set up so that there is a 20px 'margin' around it. Card also has rounded corners. CoverImage has similar constraints, with top, trailing, and leading being set to superview and bottom being defined in viewDidLoad() as 40% of the height of Card. The problem is that the width of CoverImage exceeds the width of Card, with the excess not being displayed. As a result, when I try to round the top corners of CoverImage, only the Top Left corner is rounded.
Setting leadingConstraint.constant or trailingConstraint.constant to 0 seems to have no effect, as the top right corner still remains unrounded.
How can I set CoverImage's constraints properly so that it has the correct size? Is it an issue with the constraints I'm setting in the XIB, or is there a better way to define the size of a child view?
For reference, this is the controller swift file for the View containing Card and CoverImage:
class CardViewController: UIViewController {
// MARK: Connect All Subviews/Objects
#IBOutlet weak var card: UIView!
#IBOutlet weak var coverImage: UIImageView!
#IBOutlet weak var bottomConstraint: NSLayoutConstraint!
#IBOutlet weak var topConstraint: NSLayoutConstraint!
#IBOutlet weak var trailingConstraint: NSLayoutConstraint!
#IBOutlet weak var leadingConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// MARK: Draw Card
card.layer.cornerRadius = 2
card.layer.shadowRadius = 3
card.layer.shadowOpacity = 0.15;
card.layer.shadowOffset = CGSizeMake(1, 1)
card.backgroundColor = UIColor.whiteColor()
// MARK: Draw Cover Image
let imageViewShape : CAShapeLayer = CAShapeLayer()
imageViewShape.bounds = coverImage.frame
imageViewShape.position = coverImage.center
imageViewShape.path = UIBezierPath(roundedRect: coverImage.bounds, byRoundingCorners: [UIRectCorner.TopRight, UIRectCorner.TopLeft], cornerRadii: CGSize(width: 2, height: 2)).CGPath
coverImage.layer.mask = imageViewShape
bottomConstraint.constant = card.frame.height * 0.4
}
}
Thanks to anyone who can help!
First of all, if you try to set the bounds of CAShapeLayer on viewDidLoad you'll get incorrect dimensions as for the superview isn't rendered on the device at the moment yet; it should be created on viewDidAppear.
Now that we have the correct frame we have to position it properly in superview and by default the mask we append does inherit the constraints of the view it's applied to, thus we have to adjust the origin point of it by 20 pixels on both axis.
The code I used to make it all look fine as you requested it to:
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
let imageViewShape : CAShapeLayer = CAShapeLayer()
imageViewShape.frame = coverImage.frame
imageViewShape.bounds = CGRect(origin: CGPoint(x: coverImage.bounds.origin.x + 20, y: coverImage.bounds.origin.y + 20), size: coverImage.bounds.size)
imageViewShape.path = UIBezierPath(roundedRect: coverImage.bounds, byRoundingCorners: [UIRectCorner.TopRight, UIRectCorner.TopLeft, UIRectCorner.BottomLeft, UIRectCorner.BottomRight], cornerRadii: CGSize(width: 10, height: 10)).CGPath
coverImage.layer.mask = imageViewShape
}

Swift UIScrollView - strange padding

I need to make the flowers image flipping. Images must be with the same height, but the width to set automatically. I want them to scroll right and left
Here is my code:
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate {
#IBOutlet weak var scrollView: UIScrollView!
var images = [UIImage]()
override func viewDidLoad() {
super.viewDidLoad()
scrollView.delegate = self
for i in 1...3 {
images.append(UIImage(named: "bild-0\(i).jpg")!)
}
var i: CGFloat = 0
var origin: CGFloat = 0
let height: CGFloat = scrollView.bounds.height
for image in images {
let imageView = UIImageView(frame: CGRectZero)
imageView.frame.size.height = height
imageView.image = image
imageView.sizeToFit()
imageView.frame.origin.x = origin
println(imageView.frame.size.width)
println(imageView.frame.origin.x)
println(imageView.frame.size.height)
println("asd")
origin = origin + imageView.frame.size.width
i++
scrollView.addSubview(imageView)
}
scrollView.contentSize.width = origin
scrollView.bounces = false
scrollView.pagingEnabled = false
}
}
Storyboard:
Problem (Padding from top! - Red color - is a background for UIScrollView):
Images are 765x510 300x510 and so on
UIScrollView height is 170
This is caused by scrolling insets:
Click your ViewController on Storyboard and go to file inspector, and you should see this dialog:
Untick the Adjust Scroll View Insets.

Resources