How to set imageView in circle like imageContacts in Swift correctly? - ios

I want to show a picture into imageView like the image contact (in a circle) But when I try to show this, the imageView rescale his size and this doesn't show correctly in a circle.
image.layer.borderWidth=1.0
image.layer.masksToBounds = false
image.layer.borderColor = UIColor.whiteColor().CGColor
image.layer.cornerRadius = image.frame.size.height/2
image.clipsToBounds = true
I want to show like this:
But I get this:
How can do the image resize to UIImageView size to show as a circle?
Thanks!

This is solution which I have used in my app:
var image: UIImage = UIImage(named: "imageName")
imageView.layer.borderWidth = 1.0
imageView.layer.masksToBounds = false
imageView.layer.borderColor = UIColor.whiteColor().CGColor
imageView.layer.cornerRadius = image.frame.size.width/2
imageView.clipsToBounds = true
Swift 4.0
let image = UIImage(named: "imageName")
imageView.layer.borderWidth = 1.0
imageView.layer.masksToBounds = false
imageView.layer.borderColor = UIColor.white.cgColor
imageView.layer.cornerRadius = image.frame.size.width / 2
imageView.clipsToBounds = true

What frame size are you using for image? I can get a perfect circle if I set the frame to be a square.
let image = UIImageView(frame: CGRectMake(0, 0, 100, 100))

Fast and Simple solution.
How to mask UIImage to Circle without cropping with Swift.
extension UIImageView {
public func maskCircle(anyImage: UIImage) {
self.contentMode = UIViewContentMode.ScaleAspectFill
self.layer.cornerRadius = self.frame.height / 2
self.layer.masksToBounds = false
self.clipsToBounds = true
// make square(* must to make circle),
// resize(reduce the kilobyte) and
// fix rotation.
self.image = anyImage
}
}
How to call:
let anyAvatarImage:UIImage = UIImage(named: "avatar")!
avatarImageView.maskCircle(anyAvatarImage)

Try this it's work for me ,
set imageView width and height same .
Swift
imageview?.layer.cornerRadius = (imageview?.frame.size.width ?? 0.0) / 2
imageview?.clipsToBounds = true
imageview?.layer.borderWidth = 3.0
imageview?.layer.borderColor = UIColor.white.cgColor
Screenshot
Objective C
self.imageView.layer.cornerRadius = self.imageView.frame.size.width / 2;
self.imageView.clipsToBounds = YES;
self.imageView.layer.borderWidth = 3.0f;
self.imageView.layer.borderColor = [UIColor whiteColor].CGColor;
Hope this will help to some one .

Create your custom circle UIImageView and create the circle under the layoutSubviews helps if you use Autolayout.
/*
+-------------+
| |
| |
| |
| |
| |
| |
+-------------+
The IMAGE MUST BE SQUARE
*/
class roundImageView: UIImageView {
override init(frame: CGRect) {
// 1. setup any properties here
// 2. call super.init(frame:)
super.init(frame: frame)
// 3. Setup view from .xib file
}
required init?(coder aDecoder: NSCoder) {
// 1. setup any properties here
// 2. call super.init(coder:)
super.init(coder: aDecoder)
// 3. Setup view from .xib file
}
override func layoutSubviews() {
super.layoutSubviews()
self.layer.borderWidth = 1
self.layer.masksToBounds = false
self.layer.borderColor = UIColor.white.cgColor
self.layer.cornerRadius = self.frame.size.width/2
self.clipsToBounds = true
}
}

I would suggest making your image file a perfect square to begin with. This can be done in almost any photo editing program. After that, this should work within viewDidLoad. Credit to this video
image.layer.cornerRadius = image.frame.size.width/2
image.clipsToBounds = true

That is all you need....
profilepic = UIImageView(frame: CGRectMake(0, 0, self.view.bounds.width * 0.19 , self.view.bounds.height * 0.1))
profilepic.layer.borderWidth = 1
profilepic.layer.masksToBounds = false
profilepic.layer.borderColor = UIColor.blackColor().CGColor
profilepic.layer.cornerRadius = profilepic.frame.height/2
profilepic.clipsToBounds = true

this extension really works for me (including in swift 4+)
extension UIImageView {
func roundedImage() {
self.layer.cornerRadius = (self.frame.size.width) / 2;
self.clipsToBounds = true
self.layer.borderWidth = 3.0
self.layer.borderColor = UIColor.white.cgColor
}
}
Then simply call it as
imageView.roundedImage()

If your using a UIViewController here's how do do it using Anchors. The key is to set the imageView's layer.cornerRadius in viewWillLayoutSubviews like so:
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
imageView.layer.cornerRadius = imageView.frame.size.width / 2
}
Also make sure the heightAnchor and widthAnchor are the same size. They are both 100 in my example below
Code:
let imageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.layer.borderWidth = 1.0
imageView.clipsToBounds = true
imageView.layer.borderColor = UIColor.white.cgColor
return imageView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(imageView)
imageView.heightAnchor.constraint(equalToConstant: 100).isActive = true
imageView.widthAnchor.constraint(equalToConstant: 100).isActive = true
imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
imageView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 50).isActive = true
imageView.image = UIImage(named: "pizzaImage")
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
imageView.layer.cornerRadius = imageView.frame.size.width / 2
}
If your using a CollectionView Cell set the imageView's layer.cornerRadius in layoutSubviews():
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(imageView)
imageView.heightAnchor.constraint(equalToConstant: 100).isActive = true
imageView.widthAnchor.constraint(equalToConstant: 100).isActive = true
imageView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
imageView.topAnchor.constraint(equalTo: self.topAnchor, constant: 50).isActive = true
imageView.image = UIImage(named: "pizzaImage")
}
override func layoutSubviews() {
super.layoutSubviews() // call super.layoutSubviews()
imageView.layer.cornerRadius = imageView.frame.size.width / 2
}

reviewerImage.layer.cornerRadius = reviewerImage.frame.size.width / 2;
reviewerImage.clipsToBounds = true

what i found out is that your width and height of image view must return an even number when divided by 2 to get a perfect circle e.g
let image = UIImageView(frame: CGRectMake(0, 0, 120, 120))
it should not be something like
let image = UIImageView(frame: CGRectMake(0, 0, 130, 130))

I had a similar result (more of an oval than a circle). It turned out that the constraints I set on the UIImageView forced it into an oval instead of a circle. After fixing that, the above solutions worked.

try this.
swift code
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
perform(#selector(self.setCircleForImage(_:)), with: pickedImage, afterDelay: 0)
}
#objc func setCircleForImage(_ imageView : UIImageView){
imageView.layer.cornerRadius = pickedImage.frame.size.width/2
imageView.clipsToBounds = true
}

I fixed it doing modifying the view:
Go to your Main.storyboard
Click on your image
View -> Mode -> Aspect Fill
It works perfectly

This work perfectly for me.
The order of lines is important
func circularImage(photoImageView: UIImageView?)
{
photoImageView!.layer.frame = CGRectInset(photoImageView!.layer.frame, 0, 0)
photoImageView!.layer.borderColor = UIColor.grayColor().CGColor
photoImageView!.layer.cornerRadius = photoImageView!.frame.height/2
photoImageView!.layer.masksToBounds = false
photoImageView!.clipsToBounds = true
photoImageView!.layer.borderWidth = 0.5
photoImageView!.contentMode = UIViewContentMode.ScaleAspectFill
}
How to use:
#IBOutlet weak var photoImageView: UIImageView!
...
...
circularImage(photoImageView)

This also works for me. For perfect circle result, use the same size for width and height. like image.frame = CGRect(0,0,200, 200)
For non perfect circle, width and height should not be equal like this codes below.
image.frame = CGRect(0,0,200, 160)
image.layer.borderColor = UIColor.whiteColor().CGColor
image.layer.cornerRadius = image.frame.size.height/2
image.layer.masksToBounds = false
image.layer.clipsToBounds = true
image.contentMode = .scaleAspectFill

Use this code to make image round
self.layoutIfNeeded()
self.imageView.layer.cornerRadius =
self.imageView.frame.width/2
self.imageView.layer.masksToBounds = true

You can add this file extension to your project & Don't forget to make your image Square "Width = Height" and you can grantee it by giving the image width and Aspect Ratio (1:1)
import Foundation
import UIKit
extension UIView {
#IBInspectable
var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
#IBInspectable
var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
#IBInspectable
var borderColor: UIColor? {
get {
let color = UIColor(cgColor: layer.borderColor!)
return color
}
set {
layer.borderColor = newValue?.cgColor
}
}
}
Then you will write this line in the cell or view controller or wherever you use your image:
imageViewCountryImage.cornerRadius = imageViewCountryImage.frame.height / 2
and you will find your image very super circular

// MARK: ImageView extension to make rounded
#IBDesignable extension UIImageView {
#IBInspectable var masksToBounds: Bool {
set {
layer.masksToBounds = newValue
}
get {
return layer.masksToBounds
}
}
#IBInspectable var borderWidth: CGFloat {
set {
layer.borderWidth = newValue
}
get {
return layer.borderWidth
}
}
#IBInspectable var cornerRadius: CGFloat {
set {
layer.cornerRadius = newValue
}
get {
return layer.cornerRadius
}
}
#IBInspectable var borderColor: UIColor? {
set {
guard let uiColor = newValue else { return }
layer.borderColor = uiColor.cgColor
}
get {
guard let color = layer.borderColor else { return nil }
return UIColor(cgColor: color)
}
}
}

You need to make sure the height and width should be the same as your image/view.
Like an image with 100 widths and 100 height sizes (100 X 100). If the sizes are different then the circle does not look like a circle.

You can add this extension to your code
import Foundation
import UIKit
extension UIView {
#IBInspectable
var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
#IBInspectable
var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
#IBInspectable
var borderColor: UIColor? {
get {
let color = UIColor(cgColor: layer.borderColor!)
return color
}
set {
layer.borderColor = newValue?.cgColor
}
}
}

Just add this extension
Extension:
extension UIImageView {
func circleImageView() {
layer.borderColor = UIColor.white.cgColor
layer.borderWidth = 2
contentMode = .scaleAspectFill
layer.cornerRadius = self.frame.height / 2
layer.masksToBounds = false
clipsToBounds = true
}
}
Controller:
self.imageView?.circleImageView()
One more thing, in order to make the image circle we've to set both width and height equal to each other.

Make sure that your height and width of your UIImageView is equal, or else it will look elliptical.

I have solved this problem with using these codes
private let profileAvatarImageView: UIImageView = {
let imageView = UIImageView()
imageView.clipsToBounds = true
imageView.layer.masksToBounds = true
imageView.layer.cornerRadius = imageView.frame.width/2
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.image = UIImage(systemName: "person")
imageView.backgroundColor = .black
imageView.layer.borderWidth = 2.0
imageView.layer.borderColor = UIColor.black.cgColor
return imageView
}()

Related

How to set the corner radius to 50% [duplicate]

This question already has answers here:
Set UIView's corner radius to half of the view's width automatically
(3 answers)
Closed 11 months ago.
I have an image view inside a collection view cell. I would like to set the corner radius of the image to 50% of its width (so it's a circle). How can I do this?
Here's my code so far
//
// CategoryCell.swift
// UICollectionViewDemo
//
import UIKit
final class Category3Cell: UICollectionViewCell {
private enum Constants {
// MARK: contentView layout constants
static let contentViewCornerRadius: CGFloat = 0.0
// MARK: imageView layout constants
static let imageWidth: CGFloat = 90.0
static let imageHeight: CGFloat = 90.0
// MARK: Generic layout constants
static let verticalSpacing: CGFloat = 10.0
static let horizontalPadding: CGFloat = 16.0
static let nameImagePadding: CGFloat = 20.0
}
public var categoryKey : String = "";
private let imageView: UIImageView = {
let imageView = UIImageView(frame: .zero)
imageView.contentMode = .scaleAspectFit
imageView.layer.cornerRadius = 45
imageView.layer.masksToBounds = true
return imageView
}()
private let name: UILabel = {
let label = UILabel(frame: .zero)
label.textAlignment = .center
label.numberOfLines = 0
label.font = UIFont(name: "CeraPro-Regular", size: 17);
return label
}()
override init(frame: CGRect) {
super.init(frame: .zero)
setupViews()
setupLayouts()
}
private func setupViews() {
contentView.clipsToBounds = true
contentView.layer.cornerRadius = Constants.contentViewCornerRadius
contentView.backgroundColor = .clear
contentView.isUserInteractionEnabled = true
contentView.addSubview(imageView)
contentView.addSubview(name)
}
private func setupLayouts() {
imageView.translatesAutoresizingMaskIntoConstraints = false
name.translatesAutoresizingMaskIntoConstraints = false
// Layout constraints for `imageView`
NSLayoutConstraint.activate([
imageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
imageView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
imageView.topAnchor.constraint(equalTo: contentView.topAnchor),
imageView.heightAnchor.constraint(equalToConstant: Constants.imageWidth),
imageView.heightAnchor.constraint(equalToConstant: Constants.imageHeight)
])
// Layout constraints for `usernameLabel`
NSLayoutConstraint.activate([
name.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: Constants.horizontalPadding),
name.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -Constants.horizontalPadding),
name.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: Constants.nameImagePadding)
])
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup(image: String, nameOf: String, key: String) {
imageView.image = UIImage.init(named: image)
name.text = nameOf
categoryKey = key
}
}
extension Category3Cell: ReusableView {
static var identifier: String {
return String(describing: self)
}
}
you need first the clipsToBounds set to true and then if you know the image size, you can set its layer.cornerRadius to half of that size.
Alternatively you can use the layoutSubviews method, and in its override access the imageView bounds.height and use half of this for the corner radius.
Try this code:
imageView.layer.cornerRadius = imageView.frame.height / 2
Set width and height at first, then set imageView.layer.cornerRadius = imageView.frame.height / 2.
class ViewController: UIViewController {
private let imageView: UIImageView = {
let imageView = UIImageView(frame: .zero)
imageView.contentMode = .scaleAspectFit
return imageView
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
imageView.frame = CGRect(x: 100, y: 100, width: 100, height: 100);
imageView.layer.cornerRadius = 45
imageView.layer.masksToBounds = true
self.view.addSubview(imageView)
imageView.image = UIImage.init(named: "+")
}
}

Make a circular button programatically

I want to create a circular UIButton in my iOS application.
The button is for creating a profile picture for the user.
This is the circular profile picture:
And this is how it looks like after a picture was chosen:
You can see that the button is too big and not circular.
This is my code:
func setUpProfilePicture() {
profileIcon = UIImage(named: "characteer")!
profilePicture.setImage(profileIcon, for: .normal)
profilePicture.contentMode = .scaleAspectFill
profilePicture.addTarget(self, action: #selector(handleSelectedPhoto), for: .touchUpInside)
self.view.addSubview(profilePicture)
profilePicture.translatesAutoresizingMaskIntoConstraints = false
profilePicture.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
profilePicture.topAnchor.constraint(equalTo: view.topAnchor, constant: -180).isActive = true
profilePicture.widthAnchor.constraint(equalTo: view.widthAnchor, constant: 50).isActive = true
profilePicture.heightAnchor.constraint(equalTo: view.heightAnchor, constant: 50).isActive = true
}
The chosen picture should be just filled in the circle of the profile picture character image. I worked with auto layouts, so the most tutorials I found didn't help me!
Thank you! :)
Adjust UIButton's layer:
profilePicture.imageView.contentMode = .scaleAspectFit
let cornerRadius = 25 // 50 * 0.5
profilePicture.layer.cornerRadius = cornerRadius
profilePicture.layer.masksToBounds = true
You will need to change the corner radius of your UIButton to be half of it's size
profileIcon.imageView?.contentMode = .scaleAspectFit
profileIcon.layer.cornerRadius = min(profileIcon.frame.height, profileIcon.frame.width) / 2
profileIcon.layer.masksToBounds = true
Programmatically:
private extension UIView {
func willCircle() {
self.layer.cornerRadius = min(self.frame.size.height, self.frame.size.width) * 0.5
self.layer.masksToBounds = true
self.clipsToBounds = true
}
}
usage: profilePicture.willCircle
Storyboard:
#IBInspectable
var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}

UIButton with background image, rounded corners and a shadow

I'm trying to create a UIButton with rounded corners, a background image and a shadow. Before adding the shadow, everything works fine.
But after adding shadow values, the shadow doesn't show up. Obviously due to clipsToBounds property value being set to true. If I remove that, it looks like this.
Since I need the corner radius as well, I cannot have the clipsToBounds be false.
This is my code.
class CustomButton: UIButton {
var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
clipsToBounds = true
}
}
var shadowRadius: CGFloat {
get {
return layer.shadowRadius
}
set {
layer.shadowRadius = newValue
}
}
var shadowOpacity: Float {
get {
return layer.shadowOpacity
}
set {
layer.shadowOpacity = newValue
}
}
var shadowOffset: CGSize {
get {
return layer.shadowOffset
}
set {
layer.shadowOffset = newValue
}
}
var shadowColor: UIColor? {
get {
if let color = layer.shadowColor {
return UIColor(cgColor: color)
}
return nil
}
set {
if let color = newValue {
layer.shadowColor = color.cgColor
} else {
layer.shadowColor = nil
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
}
private lazy var button: CustomButton = {
let button = CustomButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setBackgroundImage(UIImage(named: "Rectangle"), for: .normal)
button.setTitleColor(.white, for: .normal)
button.setTitle("Sign Up", for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: .semibold)
button.cornerRadius = 20
button.shadowColor = .systemGreen
button.shadowRadius = 10
button.shadowOpacity = 1
button.shadowOffset = CGSize(width: 0, height: 0)
return button
}()
Is there a workaround to have both the shadow and the corner radius?
Demo project
You can do it via adding shadow and background image with different layer.
First, if you don't need the properties, remove all and modify your CustomButton implementation just like below (modify as your need):
class CustomButton: UIButton {
private let cornerRadius: CGFloat = 20
private var imageLayer: CALayer!
private var shadowLayer: CALayer!
override func draw(_ rect: CGRect) {
addShadowsLayers(rect)
}
private func addShadowsLayers(_ rect: CGRect) {
// Add Image
if self.imageLayer == nil {
let imageLayer = CALayer()
imageLayer.frame = rect
imageLayer.contents = UIImage(named: "Rectangle")?.cgImage
imageLayer.cornerRadius = cornerRadius
imageLayer.masksToBounds = true
layer.insertSublayer(imageLayer, at: 0)
self.imageLayer = imageLayer
}
// Set the shadow
if self.shadowLayer == nil {
let shadowLayer = CALayer()
shadowLayer.masksToBounds = false
shadowLayer.shadowColor = UIColor.systemGreen.cgColor
shadowLayer.shadowOffset = .zero
shadowLayer.shadowOpacity = 1
shadowLayer.shadowRadius = 10
shadowLayer.shadowPath = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).cgPath
layer.insertSublayer(shadowLayer, at: 0)
self.shadowLayer = shadowLayer
}
}
}
And initialize your button like below:
private lazy var button: CustomButton = {
let button = CustomButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitleColor(.white, for: .normal)
button.setTitle("Sign Up", for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: .semibold)
return button
}()
You need to use two separate views for shadow and image. I can't find any solution to set image, shadow, and corner radius using the same button layer.
Make button's corner radius(clipsToBounds=true) rounded and set the image on it.
Take a shadow view under the button with proper shadow radius and offset.
You can add view.layer.masksToBounds = false
This will disable clipping for sublayer
https://developer.apple.com/documentation/quartzcore/calayer/1410896-maskstobounds

How to create a circular UIImageView

I am having issue creating a circular UIImageView. If I were to manually set the corderRadius to a value, eg. 50, it will have rounded corner. But when I try to set it as half of the frame's height or width (frame.width / 2 or frame.height / 2), it doesn't work. Somehow, the frame is (0, 0, 0, 0) when I try to print it.
And here is my code,
import UIKit
class TestIconController : UIViewController {
let icon: UIImageView = {
let imageView = UIImageView()
imageView.layer.cornerRadius = imageView.frame.width / 2
imageView.clipsToBounds = true
imageView.layer.masksToBounds = true
imageView.backgroundColor = .red
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
override func viewDidLoad() {
super.viewDidLoad()
loadLogo()
}
func loadLogo() {
view.addSubview(icon)
// Constraints
icon.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
icon.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
icon.heightAnchor.constraint(equalToConstant: 200).isActive = true
icon.widthAnchor.constraint(equalToConstant: 200).isActive = true
}
}
Override this function.
override func viewDidLayoutSubviews() {
icon.layer.cornerRadius = icon.bounds.size.width / 2
icon.clipsToBounds = true
icon.layer.masksToBounds = true
}
You may also make a base class for it for batter handling; Like
class UICirlceImageView : UIImageView {
override open func layoutSubviews() {
super.layoutSubviews();
let layer:CALayer = self.layer;
layer.cornerRadius = self.frame.size.width/2.0;
layer.masksToBounds = true;
}
}
then, do it like this
//let icon: UICirlceImageView = { // You may initialize like this as well
let icon: UIImageView = {
let imageView = UICirlceImageView()
imageView.backgroundColor = .red
//imageView.translatesAutoresizingMaskIntoConstraints = false // Don't know if it is needed
return imageView
}()
Note: The answer given by Rushabh is also correct.
You can create this extensions
extension UIImageView {
func setRounded() {
self.layer.cornerRadius = self.frame.width / 2
self.layer.masksToBounds = true
self.clipsToBounds = true
}
}
In your case you can inside viewDidLayoutSubviews call
icon.setRounded()

Swift: How to resize the font size within a UITextView while using AutoLayout?

I am one week into Swift programing and I want to build my first Application with Autolayout.
The current state of my app is that I generate a bunch of PictureCell in my ViewController. Their size is based on a slider value (and also calculated in the ViewController). This works just fine.
My struggle is customizing the inside of my PictureCell. My goal is to have a Label in the cell which font size is automatically resized when I resize the cell.
At the current state I can resize the Cell and the UITextView like I want, but I cannot resize the font within the Textview because it's constant is just called when it is initialized (I guess).
How can I address this problem in a good way?
Due to a not understanding of Swifts logic I have to post the whole code of the PictureCell:
class PictureCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
self.translatesAutoresizingMaskIntoConstraints = false
self.layer.cornerRadius = self.bounds.width / 20
self.clipsToBounds = true
setupViews()
}
let descriptionTextView: UITextView = {
let textView = UITextView()
textView.text = "Header"
textView.textColor = .black
textView.backgroundColor = .white
textView.translatesAutoresizingMaskIntoConstraints = false
textView.textAlignment = .center
textView.isEditable = false
textView.isScrollEnabled = false
textView.sizeToFit()
textView.font = UIFont.boldSystemFont(ofSize: textView.contentSize.height / 2) // Resize that
textView.layer.borderWidth = 2
textView.layer.borderColor = UIColor.red.cgColor
return textView
}()
var mainPicture: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
imageView.clipsToBounds = true
return imageView
}()
func setPictureForIndex(index: Int) {
self.mainPicture.image = UIImage(named: "color\(index)")
}
func setupViews() {
addSubview(mainPicture)
confMainPicture()
addSubview(descriptionTextView)
confDescriptionTextView()
}
func confMainPicture() {
mainPicture.translatesAutoresizingMaskIntoConstraints = false
mainPicture.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
mainPicture.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true
mainPicture.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
mainPicture.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
}
func confDescriptionTextView(){
descriptionTextView.translatesAutoresizingMaskIntoConstraints = false
descriptionTextView.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
descriptionTextView.heightAnchor.constraint(equalTo: mainPicture.heightAnchor, multiplier: 0.25).isActive = true
descriptionTextView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
}
Too small for the text
Just fine
Too big to look good
This Code solved my problem more or less:
It doesn't work properly if the Cell is really small but it's better than the starting point and maybe someone can use it.
class PictureCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
self.translatesAutoresizingMaskIntoConstraints = false
self.layer.cornerRadius = self.bounds.width / 20
self.clipsToBounds = true
setupViews()
}
//MARK: -
var cellIdetifier = Int()
var mainPicture: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
imageView.clipsToBounds = true
imageView.layer.cornerRadius = imageView.bounds.width / 20
return imageView
}()
var descriptionBox: UIView = {
let descVie = UIView()
descVie.backgroundColor = UIColor(red: 0.1 , green: 0.1, blue: 0.1, alpha: 0.5)
descVie.layer.borderWidth = 0.5
descVie.layer.borderColor = UIColor.black.cgColor
descVie.clipsToBounds = true
descVie.layer.cornerRadius = descVie.bounds.height / 5
return descVie
}()
lazy var descLabel: UITextField = {
let label = UITextField()
label.textColor = .white
label.textAlignment = .center
label.clipsToBounds = true
label.font = UIFont.systemFont(ofSize: 15)
label.adjustsFontSizeToFitWidth = true
label.autoresizingMask = [.flexibleWidth,.flexibleHeight]
label.sizeToFit()
label.layoutIfNeeded()
label.isUserInteractionEnabled = false
return label
}()
func setPictureForIndex(index: Int, name: String) {
self.descLabel.text = name
self.mainPicture.image = UIImage(named: "color\(index)")
}
// MARK: -
// MARK: Layout
func setupViews() {
addSubview(mainPicture)
addSubview(descriptionBox)
descriptionBox.addSubview(descLabel)
confBounds()
}
func confBounds() {
mainPicture.translatesAutoresizingMaskIntoConstraints = false
mainPicture.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
mainPicture.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true
mainPicture.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
mainPicture.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
descriptionBox.translatesAutoresizingMaskIntoConstraints = false
descriptionBox.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
descriptionBox.heightAnchor.constraint(equalTo: mainPicture.heightAnchor, multiplier: 0.25).isActive = true
descriptionBox.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
descriptionBox.bottomAnchor.constraint(greaterThanOrEqualTo: mainPicture.topAnchor, constant: 1)
descLabel.translatesAutoresizingMaskIntoConstraints = false
descLabel.widthAnchor.constraint(equalTo: descriptionBox.widthAnchor).isActive = true
descLabel.heightAnchor.constraint(equalTo: descriptionBox.heightAnchor).isActive = true
descLabel.bottomAnchor.constraint(equalTo: descriptionBox.bottomAnchor).isActive = true
descLabel.heightAnchor.constraint(equalTo: descriptionBox.heightAnchor).isActive = true
}
}

Resources