How to make an Image View round in Swift 5 [duplicate] - swift

This question already has answers here:
How to set image in circle in swift
(16 answers)
Closed 2 years ago.
I have used the following method to make the image rounded, but the results are not the desired ones. I have shared my code and the result in the description below. Any suggestions would be highly appreciated. Thanks!
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var image1: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
DispatchQueue.main.async(execute:{self.image1.setRounded()})
// Do any additional setup after loading the view.
}
extension UIImageView {
func setRounded() {
let radius = self.frame.width / 2
self.layer.cornerRadius = radius
self.layer.masksToBounds = true
}
}
Results :-

To make the image rounded, you have to make the height equal to the width. And then try:
extension UIImageView {
func setRounded() {
layer.cornerRadius = bounds.height/2
layer.masksToBounds = true
}
}
And call it inside viewDidLayoutSubviews.
override func viewDidLayouSubviews() {
super.viewDidLayouSubviews()
image1.setRounded()
}

Related

Map is showing nothing [duplicate]

This question already has answers here:
Programmatically Added Constraint Not Working
(2 answers)
Closed 2 years ago.
I am trying to set up the map view programmatically and i have set up the constraints down below but when i run the simulator it is just showing a blank screen. I want to pin the map view to the top,bottom,left,right in the view.
class ViewController: UIViewController {
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = .white
configureScreen()
}
let map: MKMapView = {
let map = MKMapView()
map.backgroundColor = .black
return map
}()
func configureScreen(){
view.addSubview(map)
NSLayoutConstraint.activate([
map.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor,constant: 100),
map.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor,constant: 0),
map.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor,constant: 0),
map.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor,constant: 0)
])
}
}
Because you forgot to say
map.translatesAutoresizingMaskIntoConstraints = false

Is there a way to auto layout an image in a scroll view combined with page control?

This is my first entry. I am new in app designing and from Germany, but I still hope you can understand my problem. I used Xcode 11 and Swift 5.
I am using a page control and scroll view to switch between images in one screen. It looks good on the iPhone 11 but on the iPhone 8 the width and height of the images is too great, which is why part of the first image can still be seen when the page control is on the second segment. The same happens for the with the second image and the third segment.This hopefully shows the problem.
Is there a way to fit the images to the screen size?
This is my code:
```
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate {
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var pageControl: UIPageControl!
var Pages: [String] = ["Page1","Page2","Page3"]
var frame = CGRect.zero
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
pageControl.numberOfPages = Pages.count //
setupScreens()
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.isPagingEnabled = true
scrollView.delegate = self
}
func setupScreens() {
for index in 0..<Pages.count {
// 1.
frame.origin.x = scrollView.frame.size.width * CGFloat(index)
frame.size = scrollView.frame.size
// 2.
let imageView = UIImageView(frame: frame)
imageView.image = UIImage(named: Pages[index])
self.scrollView.addSubview(imageView) }
// 3.
scrollView.contentSize = CGSize(width: (scrollView.frame.size.width * CGFloat(Pages.count)), height: scrollView.frame.size.height)
scrollView.delegate = self
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageNumber = scrollView.contentOffset.x / scrollView.frame.size.width
pageControl.currentPage = Int(pageNumber)
}
}
```
Your code is totally working fine except calling setupScreens() method in viewDidLoad().
call that method in viewDidLayoutSubviews so that it will get proper frame of scrollView.
override func viewDidLayoutSubviews() {
setupScreens()
}
Download demo from here

UICollectionViewCell drop shadow and round corners not working

I have the following code:
class ProductCell: UICollectionViewCell
{
#IBOutlet weak var productImageView: UIImageView!
func setup(productModel: ProductModel)
{
productImageView.image = productModel.image
}
override func awakeFromNib()
{
super.awakeFromNib()
layer.cornerRadius = 10
productImageView.layer.cornerRadius = layer.cornerRadius
layer.shadowOpacity = 1
layer.shadowOffset = CGSize(width: 1, height: 1)
}
}
I'm trying to add drop shadow to the collectionviewcell and also make its corners round, however, nothing happens - please see attached image.
What am I missing here? Why are the corners not round and the shadow is not also goes down a bit?
By the way - ClipToBounds on the cell is set to false
You have to set clipsToBounds = true on your productImageView so it clips the image.

In Swift’s UIKit Dynamics, how can I define a circle boundary to contain a UIView?

I have researched a LOT, but the only examples I can find anywhere are for the purpose of defining the bounds of a UIView so that they collide/bounce off each other on the OUTSIDE of the objects.
Example: A ball hits another ball and they bounce away from each other.
But what I want to do is create a circular view to CONTAIN other UIViews, such that the containing boundary is a circle, not the default square. Is there a way to achieve this?
Yes, that's totally possible. The key to achieving collision within a circle is to
Set the boundary for the collision behaviour to be a circle path (custom UIBezierPath) and
Set the animator’s referenceView to be the circle view.
Output:
Storyboard setup:
Below is the code of the view controller for the above Storyboard. The magic happens in the simulateGravityAndCollision method:
Full Xcode project
class ViewController: UIViewController {
#IBOutlet weak var redCircle: UIView!
#IBOutlet weak var whiteSquare: UIView!
var animator:UIDynamicAnimator!
override func viewDidLoad() {
super.viewDidLoad()
self.redCircle.setCornerRadius(self.redCircle.bounds.width / 2)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) { [unowned self] in
self.simulateGravityAndCollision()
}
}
func simulateGravityAndCollision() {
//The dynamic animation happens only within the reference view, i.e., our red circle view
animator = UIDynamicAnimator.init(referenceView: self.redCircle)
//Only the inside white square will be affected by gravity
let gravityBehaviour = UIGravityBehavior.init(items: [self.whiteSquare])
//We also apply collision only to the white square
let collisionBehaviour = UICollisionBehavior.init(items:[self.whiteSquare])
//This is where we create the circle boundary from the redCircle view's bounds
collisionBehaviour.addBoundary(withIdentifier: "CircleBoundary" as NSCopying, for: UIBezierPath.init(ovalIn: self.redCircle.bounds))
animator.addBehavior(gravityBehaviour)
animator.addBehavior(collisionBehaviour)
}
}
extension UIView {
open override func awakeFromNib() {
super.awakeFromNib()
self.layer.allowsEdgeAntialiasing = true
}
func setCornerRadius(_ amount:CGFloat) {
self.layer.cornerRadius = amount
self.layer.masksToBounds = true
self.clipsToBounds = true
}
}

Check text field Live

I have found this answer How to check text field input at real time?
This is what I am looking for. However I am having trouble actually implementing this code. Also my current geographical location makes googling almost impossible.
I want to be able to change the background color of the next text field if the correct number is entered into the previous text field. textfieldTwo background color will change to green if the correct value is entered in textFieldOne. If the value is incorrect then nothing will happen. Please help me out. I have two text fields called textFieldOne and textFieldTwo and nothing else in the code.
Just pop this in your main view controller in an empty project (try using iphone 6 on the simulator)
import UIKit
class ViewController: UIViewController {
var txtField:UITextField!
var txtFieldTwo:UITextField!
var rightNumber = 10
override func viewDidLoad() {
super.viewDidLoad()
//txtFieldOne
var txtField = UITextField()
txtField.frame = CGRectMake(100, 100, 200, 40)
txtField.borderStyle = UITextBorderStyle.None
txtField.backgroundColor = UIColor.blueColor()
txtField.layer.cornerRadius = 5
self.view.addSubview(txtField)
//txtFieldTwo
var txtFieldTwo = UITextField()
txtFieldTwo.frame = CGRectMake(100, 150, 200, 40)
txtFieldTwo.borderStyle = UITextBorderStyle.None
txtFieldTwo.backgroundColor = UIColor.blueColor()
txtFieldTwo.layer.cornerRadius = 5
self.view.addSubview(txtFieldTwo)
txtField.addTarget(self, action: "checkForRightNumber", forControlEvents: UIControlEvents.AllEditingEvents)
self.txtField = txtField
self.txtFieldTwo = txtFieldTwo
}
func checkForRightNumber() {
let number:Int? = self.txtField.text.toInt()
if number == rightNumber {
self.txtFieldTwo.backgroundColor = UIColor.greenColor()
} else {
self.txtFieldTwo.backgroundColor = UIColor.blueColor()
}
}
}
EDIT: Adding a version with IBOutlets and IBActions
Note that in this example the IBAction is connected to txtFieldOne on Sent Events / Editing Changed
Also, make sure your Text Fields border colors are set to None. In the storyboard, the way to do this is to choose the left most option with the dashed border around it. That's so you can color the backgrounds. You can use layer.cornerRadius to set the roundness of the border's edges.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var txtField: UITextField!
#IBOutlet weak var txtFieldTwo: UITextField!
var rightNumber = 10
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func checkForRightNumber(sender: AnyObject) {
let number:Int? = self.txtField.text.toInt()
if number == rightNumber {
self.txtFieldTwo.backgroundColor = UIColor.greenColor()
} else {
self.txtFieldTwo.backgroundColor = UIColor.blueColor()
}
}
}