Skip to content

Implementing CustomView with Code

   

Here's a sample of how to create and display a custom view in your code.
I like to implement it without using xib or storyborad, but what's best?

alt

import UIKit
class CustumView: UIView {
var imageView:UIImageView!
var label:UILabel!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = .orange
imageView = UIImageView()
imageView.image = UIImage(named: "tab-icon-sample")
imageView.backgroundColor = .red
self.addSubview(imageView)
label = UILabel()
label.text = "Hello"
label.backgroundColor = .yellow
label.textAlignment = .center
self.addSubview(label)
}
override func layoutSubviews() {
let viewWidth = frame.width
let viewHeight = frame.height
imageView.frame = CGRect(x: 0, y: 0, width: viewWidth * 0.3, height: viewHeight)
label.frame = CGRect(x: viewWidth * 0.3, y: 0, width: viewWidth * 0.3, height: viewHeight)
}
}
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
let custumView = CustumView()
custumView.frame = CGRect(x: 60, y: 60, width: 300, height: 100)
self.view.addSubview(custumView)
}
}

  1. Nested implementation of UINavigationController in UITabBarController.
  2. Implement UITabBarController.
  3. Using Color Set to manage colors in Asset Catalog
  4. I sent a code-level question to an Apple engineer.
  5. Grading the UIView background
  6. Implementing a custom button class
  7. Edit TableView to delete a Cell