I have my own custom view, ProgressBar
, which I create it programatically:
let pb = ProgressBar(frame: CGRect(x: 0, y: 0, width: 200, height: 16))
I create it using a width of 200, but then I add this to a horizontal stack view. Because of this, the view will grow depending on the screen size, for example on iPhone X will grow to 250.
Inside this custom view I am trying to use the width, but it's always 200 and it is causing all kinds of issues.
What I really need is the value that the view has inside stack view, in my case 250.
Is there a way to get that value, inside my custom view ?
Or what are my alternatives ?
edit - added some code:
class CustomTableViewCell: UITableViewCell {
func configure() {
let progressBar: ProgressBar = {
let pb = ProgressBar(frame: CGRect(x: 0, y: 0, width: 200, height: 16))
}()
}
}
And this code is called from the view controller:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1") as! CustomTableViewCell
cell.configure()
return cell
}
edit 2 - custom view code:
class ProgressBar: UIView {
var progressView: UIView = {
let v = UIView()
v.backgroundColor = .white
return v
}()
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
func configure() {
backgroundColor = UIColor(white: 1.0, alpha: 0.1)
layer.cornerRadius = 8.0
clipsToBounds = true
progressView.frame = bounds
progressView.frame.size.width = 0.0
addSubview(progressView)
}
func animate(_ pct: CGFloat) -> Void {
UIView.animate(withDuration: 1.0, animations: {
self.progressView.frame.size.width = self.bounds.size.width * pct
})
}
}
edit3 - calling animate
let progressBar: ProgressBar = {
let pb = ProgressBar(frame: CGRect(x: 0, y: 0, width: 200, height: 16))
pb.translatesAutoresizingMaskIntoConstraints = false
if data.count >= i {
if let session = data[i - 1].session {
let values = Array(session).sorted(by: { $0.date.compare($1.date) == .orderedDescending })
var sum = 0.0
for value in values {
sum += Double(value.score)
}
pb.animate(CGFloat(sum / 40)) // returns a value between 0 and 1
}
}
return pb;
}()
edit 4:
edit 5 - added debug constraints:
Printing description of $16:
<UIView: 0x107d6a100; frame = (0 0; 200 16); layer = <CALayer: 0x1d003f3c0>>
Printing description of $17:
<StepUp.ProgressBar: 0x107d6c8e0; frame = (54.3333 0; 250 16); clipsToBounds = YES; layer = <CALayer: 0x1d0220880>>