swift programmatically without storyboard
func application(application:UIApplication, didFinishLaunchingWithOptions launchOptions:NSDictionary?)->Bool{
// Override point for customization after application launch.
self.window =UIWindow(frame:UIScreen.mainScreen().bounds)varnav1=UINavigationController()varfirst=FirstViewController(nibName:nil, bundle:nil)
nav1.viewControllers =[first]varsecond=SecondViewController(nibName:nil, bundle:nil)varnav2=UINavigationController()
nav2.viewControllers =[second]vartabs=UITabBarController()
tabs.viewControllers =[nav1, nav2]self.window!.rootViewController = tabs;
self.window?.makeKeyAndVisible();
returntrue}varDynamicView=UIView(frame:CGRectMake(100,200,100,100))DynamicView.backgroundColor=UIColor.greenColor()DynamicView.layer.cornerRadius=25DynamicView.layer.borderWidth=2self.view.addSubview(DynamicView)varsliderDemo=UISlider(frame:CGRectMake(20,260,280,20))
sliderDemo.minimumValue =0
sliderDemo.maximumValue =100
sliderDemo.continuous =true
sliderDemo.tintColor =UIColor.redColor()
sliderDemo.value =50
sliderDemo.addTarget(self, action:"sliderValueDidChange:", forControlEvents:.ValueChanged)self.view.addSubview(sliderDemo)func sliderValueDidChange(sender:UISlider!){println("value--\(sender.value)")}varswitchDemo=UISwitch(frame:CGRectMake(150,300,0,0));
switchDemo.on =true
switchDemo.setOn(true, animated:false);
switchDemo.addTarget(self, action:"switchValueDidChange:", forControlEvents:.ValueChanged);
self.view.addSubview(switchDemo);
func switchValueDidChange(sender:UISwitch!){if(sender.on ==true){println(“on”)}else{println(“off”)}}from :http://www.apptuitions.com/programmatically-creating-uiview-uislider-uiswitch-using-swift/
classUberWebviewController:UIViewController{vardataFromAPI:[Any]init(data someData :[Any]){self.dataFromAPI = someData
super.init()}requiredinit(coder aDecoder:NSCoder){fatalError("init(coder:) has not been implemented")}}letviewController=UberWebviewController(data: whateverYourDataIs)self.navigationController?.presentViewController(viewController, animated:true, completion:nil)letdunamicButton=UIButton.buttonWithType(UIButtonType.System)asUIButton
dunamicButton.backgroundColor =UIColor.greenColor()
dunamicButton.setTitle("Button", forState:UIControlState.Normal)
dunamicButton.frame =CGRectMake(100,100,100,50)
dunamicButton.addTarget(self, action:"buttonTouched:", forControlEvents:UIControlEvents.TouchUpInside)self.view.addSubview(dunamicButton)func buttonTouched(sender:UIButton!){println("It Works!!!")}link: http://stackoverflow.com/questions/24030348/how-to-create-a-button-programmaticallyhttp://stackoverflow.com/questions/24102191/make-a-uibutton-programatically-in-swift
vardynamicLabel:UILabel=UILabel()
dynamicLabel.frame =CGRectMake(50,150,200,21)
dynamicLabel.backgroundColor =UIColor.orangeColor()
dynamicLabel.textColor =UIColor.blackColor()
dynamicLabel.textAlignment =NSTextAlignment.Center
dynamicLabel.text ="test label"self.view.addSubview(dynamicLabel)vardynamicTxtField:UITextField=UITextField()
dynamicTxtField.frame =CGRectMake(50,70,200,30)
dynamicTxtField.backgroundColor =UIColor.lightGrayColor()self.view.addSubview(dynamicTxtField)from:http://www.apptuitions.com/programmatically-creating-uibuttonuilabeluitextfield-using-swift/
varcustomStepper=UIStepper(frame:CGRectMake(110,250,0,0))
customStepper.wraps =true
customStepper.autorepeat =true
customStepper.maximumValue =10
customStepper.addTarget(self, action:"stepperValueChanged:", forControlEvents:.ValueChanged)self.view.addSubview(customStepper)func stepperValueChanged(sender:UIStepper!){println("It Works, Value is -->\(Int(sender.value).description)")}varcustomSegmentedControl=UISegmentedControl(items:["one","two","three"])
customSegmentedControl.frame =CGRectMake(60,250,200,30)
customSegmentedControl.selectedSegmentIndex =1
customSegmentedControl.tintColor =UIColor.redColor()
customSegmentedControl.addTarget(self, action:"segmentedValueChanged:", forControlEvents:.ValueChanged)self.view.addSubview(customSegmentedControl)func segmentedValueChanged(sender:UISegmentedControl!){println("It Works, Value is -->\(sender.selectedSegmentIndex)")}from: http://www.apptuitions.com/programmatically-creating-uistepper-and-uisegmentedcontrol-using-swift/
varimageViewObject:UIImageView
imageViewObject =UIImageView(frame:CGRectMake(0,0,100,100));
imageViewObject.image =UIImage(named:"imageName.png")self.view.addSubview(imageViewObject)
imageViewObject.contentMode =UIViewContentMode.ScaleToFill //imageViewObject.contentMode = UIViewContentMode.ScaleAspectFit //imageViewObject.contentMode = UIViewContentMode.ScaleAspectFillvartextFiled=UITextField(frame:CGRectMake(20.0,30.0,100.0,33.0))
textFiled.backgroundColor =UIColor.redColor()
textFiled.borderStyle =UITextBorderStyle.Line
self.view.addSubview(textFiled)link: http://stackoverflow.com/questions/24710041/adding-uitextfield-on-uiview-programmatically-swift
link: http://stackoverflow.com/questions/6947858/adding-uisearchbar-programmatically-to-uitableview
classTwoViewController:UIViewController,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UICollectionViewDelegate{overridefunc viewDidLoad(){
super.viewDidLoad()varflowLayout:UICollectionViewFlowLayout=UICollectionViewFlowLayout();
var__collectionView:UICollectionView?=UICollectionView(frame:CGRectMake(10,10,300,400), collectionViewLayout: flowLayout);
__collectionView?.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier:"collectionCell");
__collectionView?.delegate =self;
__collectionView?.dataSource =self;
__collectionView?.backgroundColor =UIColor.cyanColor();
self.view.addSubview(__collectionView!);
}func collectionView(collectionView:UICollectionView, numberOfItemsInSection section:Int)->Int{return20;
}func collectionView(collectionView:UICollectionView, cellForItemAtIndexPath indexPath:NSIndexPath)->UICollectionViewCell{varcell:UICollectionViewCell=collectionView.dequeueReusableCellWithReuseIdentifier("collectionCell", forIndexPath: indexPath)asUICollectionViewCell;
cell.backgroundColor =UIColor.greenColor();
return cell;
}func collectionView(collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAtIndexPath indexPath:NSIndexPath)->CGSize{returnCGSizeMake(50,50);
}func collectionView(collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, insetForSectionAtIndex section:Int)->UIEdgeInsets{returnUIEdgeInsetsMake(5,5,5,5); //top,left,bottom,right
}overridefunc didReceiveMemoryWarning(){
super.didReceiveMemoryWarning()}}link: http://stackoverflow.com/questions/17856055/creating-a-uicollectionview-programmaticallyhttp://randexdev.com/2014/07/uicollectionview/
self.window =UIWindow(frame:UIScreen.mainScreen().bounds)varnav1=UINavigationController()varmainView=ViewController(nibName:nil, bundle:nil) //ViewController = Name of your controller
nav1.viewControllers =[mainView]self.window!.rootViewController = nav1
self.window?.makeKeyAndVisible()link:
http://stackoverflow.com/questions/28793331/creating-a-navigationcontroller-programatically-swifthttp://stackoverflow.com/questions/22981610/programatically-creating-uinavigationcontroller-in-ios
overridefunc loadView(){
super.loadView()varbaseView=UIView()
baseView.backgroundColor =UIColor(red:13/255, green:44/255, blue:75/255, alpha:1)self.view = baseView
varprogressIcon=UIActivityIndicatorView()
progressIcon.setTranslatesAutoresizingMaskIntoConstraints(false)
progressIcon.activityIndicatorViewStyle =UIActivityIndicatorViewStyle.WhiteLarge
view.addSubview(progressIcon)
progressIcon.startAnimating()varconstraints=[NSLayoutConstraint]()
constraints.append(NSLayoutConstraint(
item: progressIcon,
attribute:.CenterX,
relatedBy:.Equal,
toItem: view,
attribute:.CenterX,
multiplier:1,
constant:0))
constraints.append(NSLayoutConstraint(
item: progressIcon,
attribute:.CenterY,
relatedBy:.Equal,
toItem: view,
attribute:.CenterY,
multiplier:1,
constant:0))
view.addConstraints(constraints)}link: https://coderwall.com/p/6onn0g/adding-progress-icon-programmatically-to-a-new-uiview
vartextview=UITextView(frame:CGRectMake(10,100,200,100))
textview.layer.borderWidth =1
textview.layer.borderColor =UIColor.grayColor().CGColor
self.view.addSubview(textview)
//textview.editable = false varprogressView=UIProgressView(progressViewStyle:UIProgressViewStyle.Default)
progressView.center =self.view.center
progressView.progress =0.5self.view.addSubview(progressView)
progressView.setProgress(0.8,animated:true)
progressView.progressTintColor =UIColor.greenColor()
progressView.trackTintColor =UIColor.blueColor()link: http://stackoverflow.com/questions/29758455/swift-auto-layout-programmatically-and-dynamic
link: http://stackoverflow.com/questions/26180822/swift-adding-constraints-programmatically
link: http://www.digistarters.com/swift-autolayout-and-size-classes-programmatically/
import UIKit
classViewController:UIViewController{overridefunc viewDidLoad(){
super.viewDidLoad()varalertView=UIAlertView()
alertView.title ="messageTitle"
alertView.message ="are you true to delete this item?"
alertView.addButtonWithTitle("Cannel")
alertView.addButtonWithTitle("Ok")
alertView.cannelButtonIndex =0
alertView.delegate =self
alertView.show()}func alertView(alertView:UIAlertView,clickedButtonAtIndex buttonIndex:Int){if(buttonIndex==alertView.cannelButtonIndex){printIn("you clicked cannel button")}else{printInt("you clicked Ok button")}}}import UIKit
classViewController:UIViewController,UIActionSheetDelegate{overridefunc viewDidLoad(){
super.viewDidLoad()varactionSheet=UIActionSheet()
// actionSheet.title = "the title"
actionSheet.addButtonWithTitle("cannel")
actionSheet.addButtonWithTitle("action 1")
actionSheet.addButtonWithTitle("action 2")
actionSheet.cannelButtonIndex =0
actionSheet.delegate =self
actionSheet.showInView(self.view)}func actionsheet(actionSheet:UIActionSheet!,clickedButtonAtIndex buttonIndex:Int){printInt("you clicked:"+actionSheet.buttonTitleAtIndex(buttonIndex))}}overridefunc viewDidLoad(){
super.viewDidLoad()varscrollView=UIScrollView()
scrollView.frame =self.view.bounds
varimageView=UIImageView(image:UIImage(name:"imgName"))
scrollView.contentSize = imageView.bounds.size
scrollView.addSubview(imageView)self.view.addSubview(scrollView)
// zoom
scrollView.minimumZoomScale =0.1
scrollView.maximunZoomScale =3
scrollView.delegate =self}
//UIscrollViewDelegate
func viewForZoomingInScrollView(scrollView:UIScrollView!)->UIView!{forsubview:AnyObjectin scrollView.subviews{if subview.isKindOfClass(UIImageView){return subview asUIView}}returnnil}varwebview=UIWebView(frame:CGRectMake(20,240,280,310));
varurl=NSURL(string:"http://www.google.com");
varrequest=NSURLRequest(URL: url);
webview.scalesPageToFit=true;
webview.loadRequest(request);
self.view.addSubview(webview);vardatepick=UIDatePicker(frame:CGRectMake(20,80,280,100));
datepick.datePickerMode =UIDatePickerMode.Date;
self.view.addSubview(datepick);link: http://stackoverflow.com/questions/24099230/delegates-in-swift
link: http://codewithchris.com/learn-swift-from-objective-c-part3/
link: http://stackoverflow.com/questions/24059195/delegate-in-swift-language
link: http://sledgedev.com/create-custom-delegate-and-protocol-ios-swift-objective-c/