Created
June 6, 2019 21:24
-
-
Save fadi-botros/74c078ac033fa35344e58afb7c2d37cb to your computer and use it in GitHub Desktop.
Swift trying to use manual layout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
class TryView: UIView { | |
let label: UILabel | |
let textField: UITextField | |
required init?(coder: NSCoder) { | |
fatalError("Not implemented") | |
} | |
init() { | |
label = UILabel() | |
label.text = "Some label here" | |
textField = UITextField() | |
textField.text = "Something text here" | |
super.init(frame: CGRect.zero) | |
addSubview(label) | |
addSubview(textField) | |
} | |
// Just for example, the view is not dynamic. | |
// TODO: Use structs like SwiftUI's VStack, HStack, etc... to make the view dynamic (can change layout) | |
override func layoutSubviews() { | |
let labelSize = label.sizeThatFits(bounds.size) | |
let textFieldSize = textField.sizeThatFits(bounds.size) | |
let center = CGPoint(x: bounds.midX, y: bounds.midY) | |
label.frame = CGRect(x: center.x - (labelSize.width / 2), | |
y: center.y - labelSize.height, | |
width: labelSize.width, | |
height: labelSize.height) | |
textField.frame = CGRect(x: center.x - (textFieldSize.width / 2), | |
y: center.y, | |
width: textFieldSize.width, | |
height: textFieldSize.height) | |
} | |
} | |
class TryViewController: UIViewController { | |
required init?(coder: NSCoder) { | |
fatalError("Not implemented") | |
} | |
init() { | |
super.init(nibName: nil, bundle: nil) | |
view = TryView() | |
view.backgroundColor = .white | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment