Can't set property of a UIView class - ios

I have a UIView class:
class FlashCard: UIView {
var linkedMemory: Memory? {
didSet {
frontView = showContent(of: linkedMemory!.front)
backView = showContent(of: linkedMemory!.back)
}
}
var frontView = UIView()
var backView = UIView()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
func showContent(of linkedMemory: Any) -> UIView {
var contentView = UIView()
if let image = linkedMemory as? UIImage {
let imageView = UIImageView()
imageView.image = image
contentView = imageView
}
if let text = linkedMemory as? String {
let label = UILabel()
label.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
label.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
label.text = text
contentView = label
}
return contentView
}
}
I'm trying to set its linkedMemory property in a view controller that contains this view:
#IBOutlet weak var flashCardView: FlashCard!
override func viewDidLoad() {
calcGroupFamiliarity()
flashCardView.linkedMemory = Memory(masteryLevel: 1, algorithm: Algorithm.algorithm1.chooseAlgorithm(), forgetRatio: 0, lastStudyTime: Date(), front: #imageLiteral(resourceName: "Ideas-Blue"), back: #imageLiteral(resourceName: "Ideas-Yellow"))
// See? I'm trying to change flashCardView's property here, but it never changes :(
}
Anybody has any idea on how to solve this?

Related

Fix a warning: [Camera] Attempted to change to mode Portrait with an unsupported device (BackDual)

I have a UICollectionView with a CameraCell in it as a first cell, it displays a camera preview.
I want to fix a warning in XCode console on iOS 16, iPhone XS Max with dual rear camera:
[Camera] Attempted to change to mode Portrait with an unsupported device (BackDual). Auto device for both positions unsupported, returning Auto device for same position anyway (BackAuto).
It appears after UICollectionViewCell with camera preview is displayed on a screen (not when CameraCell is created). I tried to subclass UIImagePickerController and prevent any orientation changes - didn't help.
My CameraCell code:
final class CameraCell: UICollectionViewCell {
static var reuseIdentifier: String {
String(describing: CameraCell.self)
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
NSLogIfDebug("[CameraCell] Init")
}
#available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NSLogIfDebug("[CameraCell] Deinit")
}
private lazy var imagePickerController: UIImagePickerController = {
let imgPicker = UIImagePickerController()
imgPicker.delegate = self
imgPicker.sourceType = .camera
imgPicker.cameraDevice = .rear
imgPicker.allowsEditing = false
imgPicker.showsCameraControls = false
imgPicker.cameraViewTransform = Constants.cameraViewTransform
return imgPicker
}()
private lazy var cameraContainerView: UIView = {
let view = UIView(frame: .zero)
view.clipsToBounds = true
view.translatesAutoresizingMaskIntoConstraints = false
view.isUserInteractionEnabled = true
return view
}()
private lazy var cameraView: UIView = {
// Used to return a dummy view on iPhone Simulator
let isCameraDeviceAvailable = UIImagePickerController.isCameraDeviceAvailable(UIImagePickerController.CameraDevice.rear)
guard isCameraDeviceAvailable, let view = imagePickerController.view else {
let dummyView = UIView(frame: .zero)
dummyView.translatesAutoresizingMaskIntoConstraints = false
return dummyView
}
view.frame = .zero
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private lazy var cameraImageView: UIImageView = {
let imageView = UIImageView(frame: .zero)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .center
imageView.clipsToBounds = true
imageView.image = Constants.cameraImage
imageView.backgroundColor = .surface8Color.withAlphaComponent(Constants.cameraImageViewAlpha)
imageView.isUserInteractionEnabled = true
return imageView
}()
}
// MARK: - Private
private extension CameraCell {
enum Constants {
static let cameraImageViewAlpha = 0.4 as CGFloat
static let cameraImage = UIImage(named: "photo-camera")
static let cameraViewTransform = CGAffineTransform(scaleX: 2.0, y: 2.0)
}
func setupView() {
setupCameraContainerView()
}
func setupCameraContainerView() {
addSubview(cameraContainerView)
addConstraints([
cameraContainerView.leadingAnchor.constraint(equalTo: leadingAnchor),
cameraContainerView.trailingAnchor.constraint(equalTo: trailingAnchor),
cameraContainerView.topAnchor.constraint(equalTo: topAnchor),
cameraContainerView.bottomAnchor.constraint(equalTo: bottomAnchor)
])
setupCameraView()
setupCameraImageView()
}
func setupCameraView() {
cameraContainerView.addSubview(cameraView)
addConstraints([
cameraView.leadingAnchor.constraint(equalTo: cameraContainerView.leadingAnchor),
cameraView.trailingAnchor.constraint(equalTo: cameraContainerView.trailingAnchor),
cameraView.topAnchor.constraint(equalTo: cameraContainerView.topAnchor),
cameraView.bottomAnchor.constraint(equalTo: cameraContainerView.bottomAnchor)
])
}
func setupCameraImageView() {
cameraContainerView.addSubview(cameraImageView)
addConstraints([
cameraImageView.leadingAnchor.constraint(equalTo: cameraContainerView.leadingAnchor),
cameraImageView.trailingAnchor.constraint(equalTo: cameraContainerView.trailingAnchor),
cameraImageView.topAnchor.constraint(equalTo: cameraContainerView.topAnchor),
cameraImageView.bottomAnchor.constraint(equalTo: cameraContainerView.bottomAnchor)
])
}
}
// MARK: - UIImagePickerControllerDelegate
extension CameraCell: UIImagePickerControllerDelegate {}
// MARK: - UINavigationControllerDelegate
extension CameraCell: UINavigationControllerDelegate {}

How to change color only a fraction of the total in swift?

I'm doing a QR code scan. I use UIView to change the background color of the screen to translucent color. However, I want to make the background color of the place that scans the QR code transparent. What should I do?
class QRcodeScannerViewController : UIViewController, AVCaptureMetadataOutputObjectsDelegate {
#IBOutlet weak var qrcodeView: UIView!
#IBOutlet weak var header: UINavigationBar!
#IBOutlet weak var flash: UIButton!
#IBOutlet weak var qrcodeScanArea: UIImageView!
var previewLayer: AVCaptureVideoPreviewLayer!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.black
self.qrcodeView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
view.layer.insertSublayer(previewLayer, at: 0)
view.bringSubviewToFront(flash)
view.bringSubviewToFront(header)
header.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
header.isTranslucent = true
header.backgroundColor = UIColor.clear
header.shadowImage = UIImage()
Current My QRcode ScanView
Here's the view I want:
I don't know which part I reverse, but only the color I want is black and the rest is transparent.
view.addSubview(qrcodeView)
let shape = CGRect(x: 0, y: 0, width: 200, height: 200)
let maskLayer = CAShapeLayer()
maskLayer.path = UIBezierPath(roundedRect: shape, cornerRadius: 0).cgPath
maskLayer.backgroundColor = UIColor.clear.cgColor
maskLayer.fillRule = CAShapeLayerFillRule.evenOdd
qrcodeView.layer.mask = maskLayer
I made and applied the class by referring to the answers below. But it doesn't work for me.
let focusview = FocusView.init(frame: qrcodeView.frame)
focusview.areaBackground = UIColor.black
view.addSubview(focusview)
I did something similar ... actually pretty much the same thing, some time ago.
I've dug out the code I used and have posted it here for your reference
fileprivate let focusSize: CGSize = CGSize(width: 218, height: 150)
fileprivate let focusCornerRadius: CGFloat = 10.0
class FocusView: UIView {
var areaBackground: UIColor? {
set {
maskedFocusView.backgroundColor = newValue
}
get {
return maskedFocusView.backgroundColor
}
}
fileprivate let maskedFocusView: MaskedFocusView = {
return MaskedFocusView()
}()
let focusView: UIView = {
let view = UIView()
view.layer.borderColor = UIColor.white.cgColor
view.layer.borderWidth = 2
view.layer.cornerRadius = focusCornerRadius
// view.layer.shadowColor = UIColor.white.cgColor
// view.layer.shadowRadius = 5.0
// view.layer.shadowOpacity = 0.9
// view.layer.shadowOffset = CGSize.zero
view.layer.masksToBounds = true
return view
}()
override func awakeFromNib() {
super.awakeFromNib()
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
func commonInit() {
backgroundColor = UIColor.darkGray.withAlphaComponent(0.5)
translatesAutoresizingMaskIntoConstraints = false
addSubview(maskedFocusView)
addSubview(focusView)
setupFocusViewConstraints()
setupMaskedFocusViewConstraints()
}
func setupFocusViewConstraints() {
NSLayoutConstraint.activate(
focusView.centerXAnchor.constraint(equalTo: centerXAnchor),
focusView.centerYAnchor.constraint(equalTo: centerYAnchor)
)
let regularFocusViewConstraints = [
focusView.widthAnchor.constraint(equalToConstant: focusSize.width),
focusView.heightAnchor.constraint(equalToConstant: focusSize.height)
]
NSLayoutConstraint.activate(regularFocusViewConstraints)
}
func setupMaskedFocusViewConstraints() {
NSLayoutConstraint.activate(
maskedFocusView.centerXAnchor.constraint(equalTo: centerXAnchor),
maskedFocusView.centerYAnchor.constraint(equalTo: centerYAnchor),
maskedFocusView.topAnchor.constraint(equalTo: topAnchor),
maskedFocusView.bottomAnchor.constraint(equalTo: bottomAnchor),
maskedFocusView.leadingAnchor.constraint(equalTo: leadingAnchor),
maskedFocusView.trailingAnchor.constraint(equalTo: trailingAnchor)
)
}
}
// MARK: - Masked focus view
fileprivate class MaskedFocusView: UIView {
let maskLayer: CAShapeLayer = CAShapeLayer()
override func awakeFromNib() {
super.awakeFromNib()
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
func commonInit() {
backgroundColor = UIColor.darkGray.withAlphaComponent(0.5)
maskLayer.backgroundColor = UIColor.clear.cgColor
layer.mask = maskLayer
translatesAutoresizingMaskIntoConstraints = false
}
override func layoutSubviews() {
super.layoutSubviews()
let width = bounds.width
let height = bounds.height
let x = (width - focusSize.width) / 2
let y = (height - focusSize.height) / 2
let focusRect = CGRect(x: x, y: y, width: focusSize.width, height: focusSize.height)
let fullRect = CGRect(origin: bounds.origin, size: bounds.size)
let path = CGMutablePath()
path.addPath(UIBezierPath(rect: fullRect).cgPath)
path.addPath(UIBezierPath(roundedRect: focusRect, cornerRadius: focusCornerRadius).reversing().cgPath)
maskLayer.path = path
maskLayer.fillRule = .evenOdd
}
}
// MARK: - Layout constraints extension
extension NSLayoutConstraint {
/// A helper function to activate layout constraints.
static func activate(_ constraints: NSLayoutConstraint? ...) {
for case let constraint in constraints {
guard let constraint = constraint else {
continue
}
(constraint.firstItem as? UIView)?.translatesAutoresizingMaskIntoConstraints = false
constraint.isActive = true
}
}
}
extension Array where Element: NSLayoutConstraint {
func activate() {
forEach {
if !$0.isActive {
$0.isActive = true
}
}
}
func deactivate() {
forEach {
if $0.isActive {
$0.isActive = false
}
}
}
}

Select and deselect reusable views

I create a custom view in xib file. I add 3 views(which inherited from custom) in viewController. Initially they have white color, but when i click on first view it should be changed other color and if i click on second view, the first view should be back in white color.
I need help to change first view color back to white when second view is selected.
My code for customView here
class SubscriptionView: UIView {
#IBOutlet weak var title: UILabel!
#IBOutlet weak var subTitle: UILabel!
#IBOutlet weak var checkMark: UIImageView!
var isSelect: Bool = false
let nibName = "SubscriptionView"
var contentView: UIView?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
override func awakeFromNib() {
super.awakeFromNib()
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapAction)))
}
func commonInit() {
guard let view = loadViewFromNib() else {
return
}
view.frame = self.bounds
view.layer.masksToBounds = true
view.layer.cornerRadius = 14
view.layerBorderColor = AppColor.amaranth
view.layerBorderWidth = 0.5
self.addSubview(view)
contentView = view
}
func loadViewFromNib() -> UIView? {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: nibName, bundle: bundle)
return nib.instantiate(withOwner: self, options: nil).first as? UIView
}
public func selectedView(_ isSelect: Bool) {
self.isSelect = isSelect
title.textColor = isSelect ? UIColor.white : AppColor.amaranth
subTitle.textColor = isSelect ? UIColor.white : AppColor.amaranth
checkMark.alpha = isSelect ? 1.0 : 0.0
contentView!.backgroundColor = isSelect ? AppColor.amaranth : UIColor.white
}
#objc private func tapAction() {
///????? selectedView
}
}
Here is a very simple example using the Delegate / Protocol pattern.
Define a Protocol:
// Protocol / Delegate pattern
protocol SubscriptionViewDelegate {
func gotTap(from sender: SubscriptionView)
}
Have your view controller conform to that protocol. In your custom SubscriptionView class, when the user taps you will tell the delegate that a tap was received, and the controller will loop through the SubscriptionView objects setting the "selected" state to true or false, based on the tapped view.
class SubscriptionsViewController: UIViewController, SubscriptionViewDelegate {
let theStackView: UIStackView = {
let v = UIStackView()
v.translatesAutoresizingMaskIntoConstraints = false
v.axis = .vertical
v.alignment = .fill
v.distribution = .fill
v.spacing = 20
return v
}()
// array to track the "subscription" views
var arrayOfSubscriptionViews: [SubscriptionView] = [SubscriptionView]()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .yellow
// add a stack view to hold the "subscription" views
view.addSubview(theStackView)
NSLayoutConstraint.activate([
theStackView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20.0),
theStackView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 20.0),
theStackView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20.0),
])
// instantiate 3 "subscription" views
for _ in 1...3 {
// instantiate view
let v = SubscriptionView()
// set self as its delegate
v.delegate = self
// add it to our stack view
theStackView.addArrangedSubview(v)
// append it to our tracking array
arrayOfSubscriptionViews.append(v)
}
}
func gotTap(from sender: SubscriptionView) {
// just for dev / debugging
print("got tap from", sender)
// loop through the subscription views,
// setting the sender selected to TRUE
// the others to FALSE
arrayOfSubscriptionViews.forEach {
$0.selectedView($0 == sender)
}
}
}
// Protocol / Delegate pattern
protocol SubscriptionViewDelegate {
func gotTap(from sender: SubscriptionView)
}
class SubscriptionView: UIView {
#IBOutlet weak var title: UILabel!
#IBOutlet weak var subTitle: UILabel!
#IBOutlet weak var checkMark: UIImageView!
var isSelect: Bool = false
var delegate: SubscriptionViewDelegate?
let nibName = "SubscriptionView"
var contentView: UIView?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
override func awakeFromNib() {
super.awakeFromNib()
}
func commonInit() {
guard let view = loadViewFromNib() else {
return
}
view.frame = self.bounds
view.layer.masksToBounds = true
view.layer.cornerRadius = 14
view.layer.borderColor = UIColor.red.cgColor // AppColor.amaranth
view.layer.borderWidth = 0.5
self.addSubview(view)
contentView = view
selectedView(false)
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapAction)))
}
func loadViewFromNib() -> UIView? {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: nibName, bundle: bundle)
return nib.instantiate(withOwner: self, options: nil).first as? UIView
}
public func selectedView(_ isSelect: Bool) {
self.isSelect = isSelect
title.textColor = isSelect ? UIColor.white : .red // AppColor.amaranth
subTitle.textColor = isSelect ? UIColor.white : .red // AppColor.amaranth
checkMark.alpha = isSelect ? 1.0 : 0.0
// contentView!.backgroundColor = isSelect ? AppColor.amaranth : UIColor.white
contentView!.backgroundColor = isSelect ? UIColor.red : UIColor.white
}
#objc private func tapAction() {
// for dev / debugging
print("sending tap from", self)
// tell the delegate self got tapped
delegate?.gotTap(from: self)
}
}
I only made minor changes to your SubscriptionView class, so you should be able to use it as-is with your existing .xib

Stackview Add several subviews

I try to add three subviews to a stackview. But there is only the last that I add visible. I tried to add some subviews with the constructor, but also with addArangedSubview(). Both ways I get the same result.
It looks like either the views are on top of each other or replaced by the next added one. How could I solve this and add several visible subview?
I have a view, where I create the stackview and subviews and a viewcontroller where I add this view.
View:
import UIKit
class WhatToCookView: UIView {
var originalMealButton: CustomButtonXLView!
var predefinedMealButton: CustomButtonXLView!
var ourSuggestionsButton: CustomButtonXLView!
var stackView: UIStackView!
init() {
super.init(frame:CGRect.zero)
self.backgroundColor = .gray
let transpatent = UIColor.blue.cgColor
self.originalMealButton = CustomButtonXLView(bgColorStart: transpatent, bgColorEnd: transpatent, cornerRadius: 6, mainText: "Button1", subText: "Subtext", icon: UIImage(named: "cooker_2")!)
self.predefinedMealButton = CustomButtonXLView(bgColorStart: transpatent, bgColorEnd: transpatent, cornerRadius: 6, mainText: "Button2", subText: "Subtext", icon: UIImage(named: "cooker_2")!)
self.ourSuggestionsButton = CustomButtonXLView(bgColorStart: transpatent, bgColorEnd: transpatent, cornerRadius: 6, mainText: "Button3", subText: "Subtext", icon: UIImage(named: "cooker_2")!)
self.stackView = UIStackView(arrangedSubviews: [self.originalMealButton, self.ourSuggestionsButton, self.predefinedMealButton])
self.stackView.axis = .vertical
self.stackView.distribution = .fillEqually
self.stackView.alignment = .fill
self.stackView.spacing = 10
self.stackView.backgroundColor = .green
self.addSubview(self.stackView)
self.setupButtonConstraints()
// self.stackView.addArrangedSubview(self.originalMealButton)
// self.stackView.addArrangedSubview(self.predefinedMealButton)
// self.stackView.addArrangedSubview(self.ourSuggestionsButton)
return
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupButtonConstraints() {
self.stackView.translatesAutoresizingMaskIntoConstraints = false
self.stackView.heightAnchor.constraint(equalTo:self.heightAnchor).isActive = true
self.stackView.widthAnchor.constraint(equalTo:self.widthAnchor).isActive = true
self.originalMealButton.translatesAutoresizingMaskIntoConstraints = false
self.predefinedMealButton.translatesAutoresizingMaskIntoConstraints = false
self.ourSuggestionsButton.translatesAutoresizingMaskIntoConstraints = false
}
ViewController:
import UIKit
class WhatToCookViewController: UIViewController {
var whatToCookView: WhatToCookView!
override func viewDidLoad() {
super.viewDidLoad()
self.whatToCookView = WhatToCookView()
view.addSubview(self.whatToCookView)
self.setupConstraints()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func setupConstraints() {
self.whatToCookView.translatesAutoresizingMaskIntoConstraints = false
self.whatToCookView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
self.whatToCookView.heightAnchor.constraint(equalTo:view.heightAnchor, multiplier:0.5).isActive = true
}
}
Also if I try to add arrangeSubviews not with the constructor, but with addArrangedSubview(), there is always only the last added subview visible. The result is:

Programmatically moving UILabel not working

I am having trouble changing the position of my UILabel. I can change font color and background etc but its position doesn't seem to move no matter what I try. Any help would be appreciated. Im also not using storyboard at all.
I'm fairly new to this so I'm probably missing something very obvious. I have googled and tried anything I thought applied but haven't had any luck.
View Builder:
import UIKit
class StandMapView: UIView {
var titleLabel: UILabel = UILabel()
var standMapImage: UIImageView = UIImageView()
var hotspotImage: UIImageView = UIImageView()
var hotspotTitleLabelArray: [UILabel] = []
var hotspotTextArray: [UITextView] = []
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func bind(standMap: StandMap, hotspots: [Hotspot]) {
titleLabel.text = standMap.title
standMapImage.image = UIImage(named: standMap.mapImage)
hotspotImage.image = UIImage(named:standMap.hotspotImage)
for hotspot in hotspots {
let hotspotTitle = UILabel()
let hotspotText = UITextView()
hotspotTitle.text = hotspot.title
hotspotText.text = hotspot.text
hotspotTitleLabelArray.append(hotspotTitle)
hotspotTextArray.append(hotspotText)
}
}
private func setupView() {
let screenWidth = UIScreen.mainScreen().bounds.width
let screenHeight = UIScreen.mainScreen().bounds.height
self.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
standMapImage.translatesAutoresizingMaskIntoConstraints = false
hotspotImage.translatesAutoresizingMaskIntoConstraints = false
self.backgroundColor = UIColor.blackColor()
titleLabel.sizeToFit()
titleLabel.frame = CGRect(x: screenWidth/2, y: 30, width: 0, height: 0)
titleLabel.textAlignment = .Center
titleLabel.numberOfLines = 0
titleLabel.adjustsFontSizeToFitWidth = true
titleLabel.textColor = UIColor.whiteColor()
addSubview(titleLabel)
}
}
View Controller:
import UIKit
class StandMapViewController: UIViewController {
var standMap: StandMap!
var hotspots: [Hotspot] = []
override func viewDidLoad() {
super.viewDidLoad()
Hotspot.all { hotspot in
hotspot.forEach(self.assignHotspotVariable)
}
StandMap.build {standMap in
standMap.forEach(self.assignStandMapVariable)
}
viewForStandMap(standMap, hotspots: hotspots)
}
private func assignStandMapVariable(standMap: StandMap) {
self.standMap = standMap
}
private func assignHotspotVariable(hotspot: Hotspot) {
hotspots.append(hotspot)
}
private func viewForStandMap(standMap: StandMap, hotspots: [Hotspot]) {
let standMapView = StandMapView(frame: CGRectZero)
standMapView.bind(standMap, hotspots: hotspots)
view.addSubview(standMapView)
}
}
If you want to change the position of the label, you need to change the origin x and y
titleLabel.frame.origin.x = 0.0 // put your value
titleLabel.frame.origin.y = 0.0 // put your value
self.view.layoutIfNeeded()
I managed to solve this using snapkit cocoa pod to make the constraints and then adding the subview before declaring these constraints.
Thanks for everyones help.
Heres the changes i made to the setupView function:
private func setupView() {
titleLabel.translatesAutoresizingMaskIntoConstraints = false
standMapImage.translatesAutoresizingMaskIntoConstraints = false
hotspotImage.translatesAutoresizingMaskIntoConstraints = false
self.backgroundColor = UIColor.blackColor()
titleLabel.textColor = UIColor.whiteColor()
titleLabel.textAlignment = .Center
titleLabel.numberOfLines = 0
titleLabel.adjustsFontSizeToFitWidth = true
addSubview(titleLabel)
titleLabel.snp_makeConstraints { make in
make.topMargin.equalTo(snp_topMargin).multipliedBy(60)
make.centerX.equalTo(snp_centerX)
}
}
If your label has constraints with Autolayout in storyboard, you must disable constraints to move the frame. Try using
titleLabel.translatesAutoresizingMaskIntoConstraints = YES;
Hope this may solve your issue.
If you are using AutoLayout, do following:
set outlet for constraint of UILable that you want to change.
Then change constant of that constraint as per your need.
e.g: xPosOfLable.constant = x

Resources