How make a UIScrollView Horizontal - ios

I'm working with a UIScrollView where I want to show images, but the problem is that I need those images to be shown horizontally and now they are only shown vertically, how can I change the direction of my UIScrollView, from vertical to horizontal
This is my class where you implemented the UIScrollView:
//
// fastoClass.swift
// AutoLayout(
// Created by Barbatos on 5/14/18.
// Copyright © 2018 Seccion 15. All rights reserved.
//
import UIKit
class fastoClass: UIViewController {
#IBOutlet weak var scrollHorizont: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
var constraints = [NSLayoutConstraint]()
var i = 0
var previousLeft: UIView? = nil
var previousRight: UIView? = nil
let scrollWidth: CGFloat = self.scrollHorizont.frame.size.width / 2.0
let imageColors = [UIColor.green, UIColor.lightGray, UIColor.blue, UIColor.red]
for color in imageColors{
let newImage = UIImageView()
newImage.backgroundColor = color
newImage.translatesAutoresizingMaskIntoConstraints = false
var toView : UIView? = nil
var toAttribute : NSLayoutAttribute?
let isLeft = (i % 2) == 0
if isLeft {
toView = self.scrollHorizont
toAttribute = NSLayoutAttribute.leading
} else {
toView = previousLeft
toAttribute = NSLayoutAttribute.trailing
}
var topView : UIView? = nil
var topAttribute : NSLayoutAttribute?
if i < 2 {
topView = self.scrollHorizont
topAttribute = NSLayoutAttribute.top
} else {
if isLeft {
topView = previousLeft
} else {
topView = previousRight
}
topAttribute = NSLayoutAttribute.bottom
}
let top = NSLayoutConstraint(item: newImage,
attribute: NSLayoutAttribute.top,
relatedBy: NSLayoutRelation.equal,
toItem: topView,
attribute: topAttribute!,
multiplier: 1.0,
constant: 0)
let leading = NSLayoutConstraint(item: newImage,
attribute: NSLayoutAttribute.leading,
relatedBy: NSLayoutRelation.equal,
toItem: toView,
attribute: toAttribute!,
multiplier: 1.0,
constant: 0)
let width = NSLayoutConstraint(item: newImage,
attribute: NSLayoutAttribute.width,
relatedBy: NSLayoutRelation.equal,
toItem: self.scrollHorizont,
attribute: NSLayoutAttribute.width,
multiplier: 0.5,
constant: 0)
let height = NSLayoutConstraint(item: newImage,
attribute: NSLayoutAttribute.height,
relatedBy: NSLayoutRelation.equal,
toItem: nil,
attribute: NSLayoutAttribute.notAnAttribute,
multiplier: 1.0,
constant: scrollWidth)
constraints.append(top)
constraints.append(leading)
constraints.append(width)
constraints.append(height)
self.scrollHorizont.addSubview(newImage)
i += 1
if isLeft {
previousLeft = newImage
} else {
previousRight = newImage
}
}
self.scrollHorizont.addConstraints(constraints)
self.scrollHorizont.layoutSubviews()
let contentHeight : CGFloat = scrollWidth * (CGFloat(i) / 2.0)
self.scrollHorizont.contentSize = CGSize(width: self.scrollHorizont.frame.size.width, height: contentHeight)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}

You can try this
override func viewDidAppear(_ animated: Bool) {
var constraints = [NSLayoutConstraint]()
var i = 0
var previousLeft: UIView? = nil
let imageColors = [UIColor.green, UIColor.lightGray, UIColor.blue, UIColor.red]
for color in imageColors{
let newImage = UIImageView()
newImage.backgroundColor = color
newImage.translatesAutoresizingMaskIntoConstraints = false
if previousLeft == nil {
previousLeft = scrollHorizont
}
var con:NSLayoutAttribute? = nil
if previousLeft == self.scrollHorizont {
con = NSLayoutAttribute.leading
}
else {
con = NSLayoutAttribute.trailing
}
self.scrollHorizont.addSubview(newImage)
let top = NSLayoutConstraint(item: newImage,
attribute: NSLayoutAttribute.top,
relatedBy: NSLayoutRelation.equal,
toItem: previousLeft,
attribute: NSLayoutAttribute.top,
multiplier: 1.0,
constant: 0)
let leading = NSLayoutConstraint(item: newImage,
attribute: NSLayoutAttribute.leading,
relatedBy: NSLayoutRelation.equal,
toItem: previousLeft,
attribute: con!,
multiplier: 1.0,
constant: 0)
let width = NSLayoutConstraint(item: newImage,
attribute: NSLayoutAttribute.width,
relatedBy: NSLayoutRelation.equal,
toItem: self.scrollHorizont,
attribute: NSLayoutAttribute.width,
multiplier: 1,
constant: 0)
let height = NSLayoutConstraint(item: newImage,
attribute: NSLayoutAttribute.height,
relatedBy: NSLayoutRelation.equal,
toItem: self.scrollHorizont,
attribute: NSLayoutAttribute.height,
multiplier: 1.0,
constant: 0)
if i == imageColors.count - 1 {
let tra = NSLayoutConstraint(item: newImage,
attribute: NSLayoutAttribute.trailing,
relatedBy: NSLayoutRelation.equal,
toItem: self.scrollHorizont,
attribute: NSLayoutAttribute.trailing,
multiplier: 1.0,
constant: 0)
constraints.append(tra)
}
constraints.append(top)
constraints.append(leading)
constraints.append(width)
constraints.append(height)
previousLeft = newImage
i += 1
}
self.scrollHorizont.addConstraints(constraints)
}

Related

Issue With Adding a UI Element at Runtime

I have this situation :
This pink view in the scrollview and I want is:
when I tap on 'add' button, I want that to create another pink view object (this is no problem) and set it below the first pink view object setting auto layout for it(vertical space between it and previous pink view object, trailing space .....) but I don't be able to do this part.
Can you help me?
I am not sure where you have problem adding view to scrollview. Here is example for adding button into scrollview at runtime. You can use same code for adding your pink view.
import UIKit
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate
{
var pickerviewObj : UIPickerView!=UIPickerView()
var scrlview: UIScrollView = UIScrollView();
var cotentView : UIView = UIView();
var arrdata :NSMutableArray=["1","2","3","4","5","6","7","8","9","10"]
var dctButtons : NSMutableDictionary!=NSMutableDictionary()
var ContentViewconstraintheight : NSLayoutConstraint = NSLayoutConstraint()
var xPos,ypos: NSInteger!
var SelctedTag : NSInteger!
var width: Double!
// var colors = ["Red","Yellow","Green","Blue"]
func getCalculatedHeightForScren(height : CGFloat) -> CGFloat {
return (height * self.view.frame.size.height/568 );
}
func disableAutoResizingMasks() {
self.pickerviewObj.translatesAutoresizingMaskIntoConstraints = false
self.scrlview.translatesAutoresizingMaskIntoConstraints = false
self.cotentView.translatesAutoresizingMaskIntoConstraints = false;
}
override func viewDidLoad()
{
super.viewDidLoad()
let pickerHeight = getCalculatedHeightForScren(height: 50)
self.pickerviewObj = UIPickerView(frame: CGRect(x: 0, y: self.view.frame.size.height-pickerHeight, width: self.view.frame.size.width, height: pickerHeight) )
self.view.addSubview(self.pickerviewObj);
pickerviewObj.backgroundColor = UIColor.white;
pickerviewObj.showsSelectionIndicator = true;
let toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.default;
toolBar.isTranslucent = true
toolBar.tintColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 1)
toolBar.sizeToFit()
self.view.addSubview(self.scrlview)
self.scrlview.addSubview(self.cotentView);
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.DonePicker))
toolBar.setItems([ spaceButton, doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
toolBar.frame = CGRect(x: 0, y: self.view.frame.size.height-pickerHeight-44, width: self.view.frame.size.width, height: 44);
self.view.addSubview(toolBar);
pickerviewObj.dataSource = self;
pickerviewObj.delegate = self;
//add constraints to PickerView
let constraintCenterX = NSLayoutConstraint(item: pickerviewObj, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view , attribute: NSLayoutAttribute.centerX, multiplier: 1, constant:0);
let constraintBottom = NSLayoutConstraint(item: pickerviewObj, attribute: NSLayoutAttribute.bottom , relatedBy: NSLayoutRelation.equal, toItem: self.view , attribute: NSLayoutAttribute.bottom, multiplier: 1, constant:0);
let constraintWidth = NSLayoutConstraint(item: pickerviewObj, attribute: NSLayoutAttribute.width , relatedBy: NSLayoutRelation.equal, toItem: self.view , attribute: NSLayoutAttribute.width, multiplier: 1, constant:0);
let constraintHeight = NSLayoutConstraint(item: pickerviewObj, attribute: NSLayoutAttribute.height , relatedBy: NSLayoutRelation.equal, toItem: self.view , attribute: NSLayoutAttribute.height, multiplier: (200/568), constant:0);
//add constraints to ScrollView
let scrollconstraintCenterX = NSLayoutConstraint(item: self.scrlview, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view , attribute: NSLayoutAttribute.centerX, multiplier: 1, constant:0);
let scrollconstraintBottom = NSLayoutConstraint(item: self.scrlview, attribute: NSLayoutAttribute.bottom , relatedBy: NSLayoutRelation.equal, toItem: toolBar , attribute: NSLayoutAttribute.top, multiplier: 1, constant:0);
let scrollconstraintWidth = NSLayoutConstraint(item: self.scrlview, attribute: NSLayoutAttribute.width , relatedBy: NSLayoutRelation.equal, toItem: self.view , attribute: NSLayoutAttribute.width, multiplier: 1, constant:0);
let scrollconstraintTop = NSLayoutConstraint(item: self.scrlview, attribute: NSLayoutAttribute.top , relatedBy: NSLayoutRelation.equal, toItem: self.view , attribute: NSLayoutAttribute.top, multiplier:1, constant:0);
//add constraints to ScrollView's contentView
let ContentViewconstrainttop = NSLayoutConstraint(item: self.cotentView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self.scrlview , attribute: NSLayoutAttribute.topMargin, multiplier: 1, constant:0);
let ContentViewconstraintBottom = NSLayoutConstraint(item: self.cotentView, attribute: NSLayoutAttribute.bottom , relatedBy: NSLayoutRelation.equal, toItem: self.scrlview , attribute: NSLayoutAttribute.bottomMargin, multiplier: 1, constant:0);
let ContentViewconstraintleft = NSLayoutConstraint(item: self.cotentView, attribute: NSLayoutAttribute.trailing , relatedBy: NSLayoutRelation.equal, toItem: self.scrlview , attribute: NSLayoutAttribute.trailing, multiplier: 1, constant:0);
let ContentViewconstraintright = NSLayoutConstraint(item: self.cotentView, attribute: NSLayoutAttribute.leading , relatedBy: NSLayoutRelation.equal, toItem: self.scrlview , attribute: NSLayoutAttribute.leading, multiplier: (200/568), constant:0);
let ContentViewconstraintWidth = NSLayoutConstraint(item: self.cotentView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: self.scrlview , attribute: NSLayoutAttribute.width, multiplier: 1, constant:0);
self.ContentViewconstraintheight = NSLayoutConstraint(item: self.cotentView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil , attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant:100);
//add constraints to toolBar
let toolconstraintCenterX = NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view , attribute: NSLayoutAttribute.centerX, multiplier: 1, constant:0);
let toolconstraintBottom = NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.bottom , relatedBy: NSLayoutRelation.equal, toItem: self.pickerviewObj , attribute: NSLayoutAttribute.top, multiplier: 1, constant:0);
let toolconstraintWidth = NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.width , relatedBy: NSLayoutRelation.equal, toItem: self.view , attribute: NSLayoutAttribute.width, multiplier: 1, constant:0);
//activare all constraints
NSLayoutConstraint.activate([constraintWidth,constraintHeight,constraintCenterX,constraintBottom,toolconstraintWidth,toolconstraintBottom,toolconstraintCenterX,scrollconstraintTop,scrollconstraintWidth,scrollconstraintCenterX,scrollconstraintBottom,ContentViewconstrainttop,ContentViewconstraintBottom,ContentViewconstraintleft,ContentViewconstraintright,ContentViewconstraintWidth,self.ContentViewconstraintheight]);
self.view.layoutSubviews()
self.disableAutoResizingMasks();
toolBar.translatesAutoresizingMaskIntoConstraints = false
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
func getSorted(s1 : Any , s2 : Any) -> Bool{
let str1 : String = s1 as! String
let str2 : String = s2 as! String
return Int(str1)! < Int(str2)!;
}
//custom Logics to Update UI
func addConstarintsToButton(btn : UIButton , yPos : CGFloat)
{
NSLayoutConstraint.deactivate(btn.constraints);
btn.removeConstraints(btn.constraints);
let width = ((self.view.frame.size.width-20)/2) - 30;
let height = self.getCalculatedHeightForScren(height: 40);
let constraintCenterX = NSLayoutConstraint(item: btn, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.scrlview , attribute: NSLayoutAttribute.centerX, multiplier: 1, constant:0);
let constrainttop = NSLayoutConstraint(item: btn, attribute: NSLayoutAttribute.top , relatedBy: NSLayoutRelation.equal, toItem: self.cotentView , attribute: NSLayoutAttribute.top, multiplier: 1, constant:yPos);
let constraintWidth = NSLayoutConstraint(item: btn, attribute: NSLayoutAttribute.width , relatedBy: NSLayoutRelation.equal, toItem: nil , attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: width);
let constraintHeight = NSLayoutConstraint(item: btn, attribute: NSLayoutAttribute.height , relatedBy: NSLayoutRelation.equal, toItem: nil , attribute: NSLayoutAttribute.notAnAttribute, multiplier: height, constant:height);
NSLayoutConstraint.activate([constraintCenterX, constrainttop,constraintWidth,constraintHeight])
btn.translatesAutoresizingMaskIntoConstraints = false
}
func updateUIElements(tag : Int)
{
let arrKeys : NSMutableArray = NSMutableArray(array: dctButtons.allKeys, copyItems: true)
let SortedKeys = arrKeys.sorted(by: getSorted)
var xPos :CGFloat = 10.0;
var yPos :CGFloat = 50.0;
let width = ((self.view.frame.size.width-20)/2) - 30;
let height = self.getCalculatedHeightForScren(height: 40);
xPos = (self.view.frame.size.width - width)/2;
UIView.animate(withDuration: 0.5, animations: {
if(tag > 0)
{
let vw = self.cotentView.viewWithTag(tag)
vw?.removeFromSuperview()
let vw1 = self.cotentView.viewWithTag(tag + 100)
vw1?.removeFromSuperview()
}
for key in SortedKeys {
let btn1 = self.dctButtons.object(forKey: key) as! UIButton
btn1.frame = CGRect( x:xPos, y:yPos,width:width,height:height);
if let testBtn = self.cotentView.viewWithTag(btn1.tag+100) as? UIButton
{
let btnCross = testBtn ;
btnCross.frame = CGRect(x: xPos + btn1.frame.size.width + 5, y: yPos, width: 20, height: height);
}
self.ContentViewconstraintheight.constant = btn1.frame.size.height + 100;
if let vw = self.cotentView.viewWithTag(btn1.tag) as? UIButton
{
vw.removeFromSuperview();
self.cotentView.addSubview(btn1);
self.addConstarintsToButton(btn: btn1, yPos: yPos);
}
else{
self.cotentView.addSubview(btn1);
self.addConstarintsToButton(btn: btn1, yPos: yPos);
}
yPos += height + 10
}
self.view.layoutSubviews()
self.ContentViewconstraintheight.constant = yPos ;
})
}
// Control event Methods....
func btnClick(sender: UIButton!)
{
SelctedTag=sender.tag;
print(SelctedTag)
if sender.isSelected
{
return;
}
sender.isSelected = true;
let ButtonClose = UIButton(frame: CGRect(x: sender.frame.origin.x + sender.frame.size.width + 5, y: sender.frame.origin.y, width: 20, height: sender.frame.size.height) )
ButtonClose.tag = sender.tag + 100;
ButtonClose.setTitle("X", for: UIControlState.normal)
ButtonClose.backgroundColor = UIColor.gray
ButtonClose.setTitleColor(UIColor.red, for: UIControlState.normal);
ButtonClose.isUserInteractionEnabled = true;
ButtonClose.addTarget(self, action: #selector(ViewController.btnClose(sender:)), for: UIControlEvents.touchUpInside);
self.cotentView.addSubview(ButtonClose);
let strVal = String(sender.tag)
self.arrdata.remove(strVal)
self.pickerviewObj.reloadComponent(0);
}
func DonePicker()
{
let selectedIndex = self.pickerviewObj.selectedRow(inComponent: 0);
if (arrdata.count == 0 || selectedIndex < 0 || selectedIndex > arrdata.count )
{
return;
}
let x : String = arrdata[selectedIndex] as! String
let tag = Int(x)!
if let vw = self.cotentView.viewWithTag(tag) as? UIButton
{
return;
}
let btn = UIButton(type: UIButtonType.system);
btn.isSelected = false;
btn.tag = tag
btn.backgroundColor = UIColor.black;
btn.setTitleColor(UIColor.white, for: UIControlState.normal)
btn.addTarget(self, action:#selector(ViewController.btnClick(sender:)), for: UIControlEvents.touchUpInside)
btn.setTitle("Field " + String(x), for: UIControlState.normal)
btn.setTitleColor(UIColor.white, for: UIControlState.normal)
btn.isUserInteractionEnabled = true;
btn.center = self.pickerviewObj.center;
dctButtons.setObject(btn, forKey: String(x) as NSCopying)
self.pickerviewObj.reloadComponent(0);
self.updateUIElements(tag: 0);
}
func btnClose(sender: UIButton!)
{
print((SelctedTag))
let key = String(sender.tag - 100);
dctButtons.removeObject(forKey: key);
arrdata.add( key)
let tmpArray = arrdata.sorted(by: getSorted)
arrdata.removeAllObjects();
arrdata.addObjects(from: tmpArray)
self.pickerviewObj.reloadComponent(0);
self.updateUIElements(tag: sender.tag - 100);
}
// Picker view Methods....
func numberOfComponents(in pickerView: UIPickerView) -> Int
{
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
{
return arrdata.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
{
let x : String = arrdata[row] as! String
return "Field " + x
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
// let x : Int = arrdata[row] as! Int
// arrButton.add(x)
// print(arrButton)
// self .numberOfButton(number: arrdata[row] as! Int)
// arrdata.removeObject(at: row)
// pickerView.reloadAllComponents()
}
}

Programmatically adding constraints for a UILabel for a circular load animation

I am trying to add a label programmatically inside a circular loading image that I created using Open Source software. The problem I am facing is that I do not know how to constrain the label such that it is contained within the circle. I am trying to compare a CAShapeLayer to a UILabel, but this isn't going to work because CAShapeLayer is not a type available from Storyboard. Is there a suggested fix I should follow?
let circlePathLayer = CAShapeLayer()
var circleRadius: CGFloat = 100.0
var circleCenter: CGPoint = CGPoint()
func displayStatus() {
let statusLabel = UILabel(frame: CGRectMake(0, 0, 200, 21))
statusLabel.center = CGPointMake(160, 284)
statusLabel.textAlignment = NSTextAlignment.Center
statusLabel.textColor = UIColor.whiteColor()
statusLabel.text = "(Up)loading"
let horizontalConstraint = NSLayoutConstraint(item: statusLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: circlePathLayer, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0) //ERROR
self.addConstraint(horizontalConstraint)
let verticalConstraint = NSLayoutConstraint(item: statusLabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: circlePathLayer, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0) //ERROR
self.addConstraint(verticalConstraint)
self.addSubview(statusLabel)
}
Remove this Code:
let horizontalConstraint = NSLayoutConstraint(item: statusLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: circlePathLayer, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0) //ERROR
self.addConstraint(horizontalConstraint)
let verticalConstraint = NSLayoutConstraint(item: statusLabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: circlePathLayer, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0) //ERROR
self.addConstraint(verticalConstraint)
Add this Code:
Objectice C:
- (void)layoutSubviews
{
[super layoutSubviews];
statusLabel.center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds))
}
Swift:
override func layoutSubviews() {
super.layoutSubviews()
statusLabel.center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidX(self.bounds))
}

How can I make the type emoji or type anything

I am currently working on a custom keyboard
and I encountered a problem when I try to combine the textDocumentProxy in a new window
So have add emoji keyboard button
  and which I pass page with the addition of two buttons of emoji Now my problem is how I can incorporate textDocumentProxy another window or link between them waned even can type emoji
I try to type anything not only emoji
Full source code is here
https://github.com/archagon/tasty-imitation-keyboard
import UIKit
class DefaultSettings1: ExtraView, UITableViewDelegate {
#IBOutlet var tableView1: UITableView?
#IBOutlet var effectsView: UIVisualEffectView?
#IBOutlet var backButton1: UIButton?
#IBOutlet var settingsLabel: UILabel?
#IBOutlet var pixelLine: UIView?
#IBOutlet var keyPressed: UIButton?
override var darkMode: Bool {
didSet {
self.updateAppearance(darkMode)
}
}
let cellBackgroundColorDark = UIColor.whiteColor().colorWithAlphaComponent(CGFloat(0.25))
let cellBackgroundColorLight = UIColor.whiteColor().colorWithAlphaComponent(CGFloat(1))
let cellLabelColorDark = UIColor.whiteColor()
let cellLabelColorLight = UIColor.blackColor()
let cellLongLabelColorDark = UIColor.lightGrayColor()
let cellLongLabelColorLight = UIColor.grayColor()
// TODO: these probably don't belong here, and also need to be localized
required init(globalColors: GlobalColors.Type?, darkMode: Bool, solidColorMode: Bool) {
super.init(globalColors: globalColors, darkMode: darkMode, solidColorMode: solidColorMode)
self.loadNib()
}
required init(coder aDecoder: NSCoder) {
fatalError("loading from nib not supported")
}
func loadNib() {
let assets = NSBundle(forClass: self.dynamicType).loadNibNamed("DefaultSettings1", owner: self, options: nil)
if assets.count > 0 {
if var rootView = assets.first as? UIView {
rootView.setTranslatesAutoresizingMaskIntoConstraints(false)
self.addSubview(rootView)
let left = NSLayoutConstraint(item: rootView, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0)
let right = NSLayoutConstraint(item: rootView, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0)
let top = NSLayoutConstraint(item: rootView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0)
let bottom = NSLayoutConstraint(item: rootView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)
self.addConstraint(left)
self.addConstraint(right)
self.addConstraint(top)
self.addConstraint(bottom)
}
}
self.tableView1?.registerClass(DefaultSettings1TableViewCell.self, forCellReuseIdentifier: "cell")
self.tableView1?.estimatedRowHeight = 44;
self.tableView1?.rowHeight = UITableViewAutomaticDimension;
// XXX: this is here b/c a totally transparent background does not support scrolling in blank areas
self.tableView1?.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.01)
self.updateAppearance(self.darkMode)
}
func tableView1(tableView1: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if var cell = tableView1.dequeueReusableCellWithIdentifier("cell") as? DefaultSettings1TableViewCell {
if cell.sw.allTargets().count == 0 {
cell.sw.addTarget(self, action: Selector("toggleSetting1:"), forControlEvents: UIControlEvents.ValueChanged)
}
cell.backgroundColor = (self.darkMode ? cellBackgroundColorDark : cellBackgroundColorLight)
cell.label.textColor = (self.darkMode ? cellLabelColorDark : cellLabelColorLight)
cell.longLabel.textColor = (self.darkMode ? cellLongLabelColorDark : cellLongLabelColorLight)
cell.changeConstraints()
return cell
}
else {
assert(false, "this is a bad thing that just happened")
return UITableViewCell()
}
}
func updateAppearance(dark: Bool) {
if dark {
self.effectsView?.effect
let blueColor = UIColor(red: 135/CGFloat(255), green: 206/CGFloat(255), blue: 250/CGFloat(255), alpha: 1)
self.pixelLine?.backgroundColor = blueColor.colorWithAlphaComponent(CGFloat(0.5))
self.backButton1?.setTitleColor(blueColor, forState: UIControlState.Normal)
self.settingsLabel?.textColor = UIColor.whiteColor()
if let visibleCells = self.tableView1?.visibleCells() {
for cell in visibleCells {
if var cell = cell as? UITableViewCell {
cell.backgroundColor = cellBackgroundColorDark
var label = cell.viewWithTag(2) as? UILabel
label?.textColor = cellLabelColorDark
var longLabel = cell.viewWithTag(3) as? UITextView
longLabel?.textColor = cellLongLabelColorDark
}
}
}
}
else {
let blueColor = UIColor(red: 0/CGFloat(255), green: 122/CGFloat(255), blue: 255/CGFloat(255), alpha: 1)
self.pixelLine?.backgroundColor = blueColor.colorWithAlphaComponent(CGFloat(0.5))
self.backButton1?.setTitleColor(blueColor, forState: UIControlState.Normal)
self.settingsLabel?.textColor = UIColor.grayColor()
if let visibleCells = self.tableView1?.visibleCells() {
for cell in visibleCells {
if var cell = cell as? UITableViewCell {
cell.backgroundColor = cellBackgroundColorLight
var label = cell.viewWithTag(2) as? UILabel
label?.textColor = cellLabelColorLight
var longLabel = cell.viewWithTag(3) as? UITextView
longLabel?.textColor = cellLongLabelColorLight
}
}
}
}
}
}
class DefaultSettings1TableViewCell: UITableViewCell {
var sw: UISwitch
var label: UILabel
var longLabel: UITextView
var constraintsSetForLongLabel: Bool
var cellConstraints: [NSLayoutConstraint]
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
self.sw = UISwitch()
self.label = UILabel()
self.longLabel = UITextView()
self.cellConstraints = []
self.constraintsSetForLongLabel = false
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.sw.setTranslatesAutoresizingMaskIntoConstraints(false)
self.label.setTranslatesAutoresizingMaskIntoConstraints(false)
self.longLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
self.longLabel.text = nil
self.longLabel.scrollEnabled = false
self.longLabel.selectable = false
self.longLabel.backgroundColor = UIColor.clearColor()
self.sw.tag = 1
self.label.tag = 2
self.longLabel.tag = 3
self.addSubview(self.sw)
self.addSubview(self.label)
self.addSubview(self.longLabel)
self.addConstraints()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addConstraints() {
let margin: CGFloat = 8
let sideMargin = margin * 2
let hasLongText = self.longLabel.text != nil && !self.longLabel.text.isEmpty
if hasLongText {
let switchSide = NSLayoutConstraint(item: sw, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: -sideMargin)
let switchTop = NSLayoutConstraint(item: sw, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: margin)
let labelSide = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: sideMargin)
let labelCenter = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: sw, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
self.addConstraint(switchSide)
self.addConstraint(switchTop)
self.addConstraint(labelSide)
self.addConstraint(labelCenter)
let left = NSLayoutConstraint(item: longLabel, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: sideMargin)
let right = NSLayoutConstraint(item: longLabel, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: -sideMargin)
let top = NSLayoutConstraint(item: longLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: sw, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: margin)
let bottom = NSLayoutConstraint(item: longLabel, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -margin)
self.addConstraint(left)
self.addConstraint(right)
self.addConstraint(top)
self.addConstraint(bottom)
self.cellConstraints += [switchSide, switchTop, labelSide, labelCenter, left, right, top, bottom]
self.constraintsSetForLongLabel = true
}
else {
let switchSide = NSLayoutConstraint(item: sw, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: -sideMargin)
let switchTop = NSLayoutConstraint(item: sw, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: margin)
let switchBottom = NSLayoutConstraint(item: sw, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -margin)
let labelSide = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: sideMargin)
let labelCenter = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: sw, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
self.addConstraint(switchSide)
self.addConstraint(switchTop)
self.addConstraint(switchBottom)
self.addConstraint(labelSide)
self.addConstraint(labelCenter)
self.cellConstraints += [switchSide, switchTop, switchBottom, labelSide, labelCenter]
self.constraintsSetForLongLabel = false
}
}
// XXX: not in updateConstraints because it doesn't play nice with UITableViewAutomaticDimension for some reason
func changeConstraints() {
let hasLongText = self.longLabel.text != nil && !self.longLabel.text.isEmpty
if hasLongText != self.constraintsSetForLongLabel {
self.removeConstraints(self.cellConstraints)
self.cellConstraints.removeAll()
self.addConstraints()
}
}
}
You need to change many things into your project as per your requirement like you can use that setting view by hiding that tableView and add one UIView on it after that you can add emojis into that view and when user click on setting button from keyboard you can hide your emojis view and show tableview but when user want to type smiles that you don't need to hide anything just show your emojis view.
HERE is your updated project.

Check for Truncation in UILabel - iOS, Swift

I'm working on an app in swift. Currently, I'm working on the population of a table view with custom cells, see screenshot. However, right now I have the text set so that the title is exactly 2 lines and the summary is exactly 3 lines. By doing this, the text is sometimes truncated. Now, I want to set the priority for text in the title, so that if the title is truncated when it is 2 lines long I expand it to 3 lines and make the summary only 2 lines. I tried doing this with auto layout, but failed. Now I tried the following approach, according to this and this, but the function below also didn't seem to accurately determine if the text is truncated.
func isTruncated(label:UILabel) -> Bool {
let context = NSStringDrawingContext()
let text : NSAttributedString = NSAttributedString(string: label.text!, attributes: [NSFontAttributeName : label.font])
let labelSize : CGSize = CGSize(width: label.frame.width, height: CGFloat.max)
let options : NSStringDrawingOptions = unsafeBitCast(NSStringDrawingOptions.UsesLineFragmentOrigin.rawValue | NSStringDrawingOptions.UsesFontLeading.rawValue, NSStringDrawingOptions.self)
let labelRect : CGRect = text.boundingRectWithSize(labelSize, options: options, context: context)
if Float(labelRect.height/label.font.lineHeight) > Float(label.numberOfLines) {
return true
} else {
return false
}
}
Can anybody help? How can I change my function to make this work? Or should work with different auto layout constraints and how?
Thanks so much!
EDIT:
this is my current code. Some auto layout is done is the storyboard, however the changing auto layout is done in code.
import UIKit
class FeedTableViewCell: UITableViewCell {
var thumbnailImage = UIImageView()
#IBOutlet var titleText: UILabel!
#IBOutlet var summaryText: UILabel!
#IBOutlet var sourceAndDateText: UILabel!
var imgTitleConst = NSLayoutConstraint()
var imgSummaryConst = NSLayoutConstraint()
var imgDetailConst = NSLayoutConstraint()
var titleConst = NSLayoutConstraint()
var summaryConst = NSLayoutConstraint()
var detailConst = NSLayoutConstraint()
var titleHeightConst = NSLayoutConstraint()
var summaryHeightConst = NSLayoutConstraint()
var imageRemoved = false
var titleConstAdd = false
override func awakeFromNib() {
super.awakeFromNib()
thumbnailImage.clipsToBounds = true
summaryText.clipsToBounds = true
titleText.clipsToBounds = true
sourceAndDateText.clipsToBounds = true
addImage()
}
func removeImage() {
if let viewToRemove = self.viewWithTag(123) {
imageRemoved = true
viewToRemove.removeFromSuperview()
self.contentView.removeConstraints([imgTitleConst, imgSummaryConst, imgDetailConst])
titleConst = NSLayoutConstraint(item: self.titleText, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.contentView, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 14)
summaryConst = NSLayoutConstraint(item: summaryText, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.contentView, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 14)
detailConst = NSLayoutConstraint(item: sourceAndDateText, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.contentView, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 14)
self.contentView.addConstraints([titleConst, detailConst, summaryConst])
setNumberOfLines()
self.contentView.layoutSubviews()
}
}
func addImage() {
thumbnailImage.tag = 123
thumbnailImage.image = UIImage(named: "placeholder")
thumbnailImage.frame = CGRectMake(14, 12, 100, 100)
thumbnailImage.contentMode = UIViewContentMode.ScaleAspectFill
thumbnailImage.clipsToBounds = true
self.contentView.addSubview(thumbnailImage)
if imageRemoved {
self.contentView.removeConstraints([titleConst, summaryConst, detailConst])
}
var widthConst = NSLayoutConstraint(item: thumbnailImage, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 100)
var heightConst = NSLayoutConstraint(item: thumbnailImage, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 100)
var leftConst = NSLayoutConstraint(item: thumbnailImage, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.contentView, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 14)
var topConst = NSLayoutConstraint(item: thumbnailImage, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.contentView, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 12)
imgTitleConst = NSLayoutConstraint(item: self.titleText, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.thumbnailImage, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 8)
imgSummaryConst = NSLayoutConstraint(item: summaryText, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.thumbnailImage, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 8)
imgDetailConst = NSLayoutConstraint(item: sourceAndDateText, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.thumbnailImage, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 8)
self.contentView.addConstraints([widthConst, heightConst, leftConst, topConst, imgTitleConst, imgSummaryConst, imgDetailConst])
setNumberOfLines()
self.contentView.layoutSubviews()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setNumberOfLines() {
if titleConstAdd {
self.contentView.removeConstraints([titleHeightConst, summaryHeightConst])
}
if titleText.numberOfLines == 3 {
titleText.numberOfLines = 2
}
if countLabelLines(titleText) > 2 {
titleText.numberOfLines = 3
summaryText.numberOfLines = 2
println("adjusting label heigh to be taller")
titleHeightConst = NSLayoutConstraint(item: titleText, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 51)
summaryHeightConst = NSLayoutConstraint(item: summaryText, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 32)
self.contentView.addConstraints([titleHeightConst, summaryHeightConst])
} else {
titleText.numberOfLines = 2
summaryText.numberOfLines = 3
titleHeightConst = NSLayoutConstraint(item: titleText, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 36)
summaryHeightConst = NSLayoutConstraint(item: summaryText, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 47)
self.contentView.addConstraints([titleHeightConst, summaryHeightConst])
}
titleConstAdd = true
}
}
func countLabelLines(label:UILabel)->Int{
if let text = label.text{
// cast text to NSString so we can use sizeWithAttributes
var myText = text as NSString
//Set attributes
var attributes = [NSFontAttributeName : UIFont.boldSystemFontOfSize(14)]
//Calculate the size of your UILabel by using the systemfont and the paragraph we created before. Edit the font and replace it with yours if you use another
var labelSize = myText.boundingRectWithSize(CGSizeMake(label.bounds.width, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes, context: nil)
//Now we return the amount of lines using the ceil method
var lines = ceil(CGFloat(labelSize.height) / label.font.lineHeight)
println(labelSize.height)
println("\(lines)")
return Int(lines)
}
return 0
}
You can use the sizeWithAttributes method from NSString to get the number of lines your UILabel has. You will have to cast your label text to NSString first to use this method:
func countLabelLines(label:UILabel)->Int{
if let text = label.text{
// cast text to NSString so we can use sizeWithAttributes
var myText = text as NSString
//A Paragraph that we use to set the lineBreakMode.
var paragraph = NSMutableParagraphStyle()
//Set the lineBreakMode to wordWrapping
paragraph.lineBreakMode = NSLineBreakMode.ByWordWrapping
//Calculate the size of your UILabel by using the systemfont and the paragraph we created before. Edit the font and replace it with yours if you use another
var labelSize = myText.sizeWithAttributes([NSFontAttributeName : UIFont.systemFontOfSize(17), NSParagraphStyleAttributeName : paragraph.copy()])
//Now we return the amount of lines using the ceil method
var lines = ceil(CGFloat(size.height) / label.font.lineHeight)
return Int(lines)
}
return 0
}
Edit
If this method doesn't work for you because your label hasn't a fixed width, you can use boundingRectWithSize to get the size of the label and use that with the ceil method.
func countLabelLines(label:UILabel)->Int{
if let text = label.text{
// cast text to NSString so we can use sizeWithAttributes
var myText = text as NSString
//Set attributes
var attributes = [NSFontAttributeName : UIFont.systemFontOfSize(UIFont.systemFontSize())]
//Calculate the size of your UILabel by using the systemfont and the paragraph we created before. Edit the font and replace it with yours if you use another
var labelSize = myText.boundingRectWithSize(CGSizeMake(label.bounds.width, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes, context: nil)
//Now we return the amount of lines using the ceil method
var lines = ceil(CGFloat(labelSize.height) / label.font.lineHeight)
return Int(lines)
}
return 0
}
Swift 3
A simple solution is counting the number of lines after assigning the string and compare to the max number of lines of the label.
import Foundation
import UIKit
extension UILabel {
func countLabelLines() -> Int {
// Call self.layoutIfNeeded() if your view is uses auto layout
let myText = self.text! as NSString
let attributes = [NSFontAttributeName : self.font]
let labelSize = myText.boundingRect(with: CGSize(width: self.bounds.width, height: CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attributes, context: nil)
return Int(ceil(CGFloat(labelSize.height) / self.font.lineHeight))
}
func isTruncated() -> Bool {
if (self.countLabelLines() > self.numberOfLines) {
return true
}
return false
}
}
This works for labels with fixed width and fixed number of lines or fixed height:
extension UILabel {
func willBeTruncated() -> Bool {
let label:UILabel = UILabel(frame: CGRectMake(0, 0, self.bounds.width, CGFloat.max))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.font = self.font
label.text = self.text
label.sizeToFit()
if label.frame.height > self.frame.height {
return true
}
return false
}
}

IOS 8 keyboard how to swap between the decimal and numeric keyboard + shift key

I am busy making an IOS 8 keyboard and I need some help.
I have made a basic keyboard and everything works fine but I have a bumps and I need some help to slove them. I wrote the code in swift(keep in mind I'm new to swift).
I need help with the following:
To swap the keyboard from decimal(the normal one with letters) to numeric(the number/symbol one) I wrote some code for it (It basically hides the keyboards respectively and shows them again) but I don't know how to make it run when I tap the "123" button.
When I type a key eg. "A" it prints out exactly how it appears on the keyboard how can I make it automatically lowercase and then implement a shift button to give me capital letters?
Some help to solve this would be much appreciated.
Here is the code I have so far:
import UIKit
class KeyboardViewController: UIInputViewController
{
#IBOutlet var nextKeyboardButton: UIButton!
var allButtons = [UIButton]()
override func updateViewConstraints()
{
super.updateViewConstraints()
// Add custom view sizing constraints here
}
override func viewDidLoad()
{
//Normal Keyboard start
super.viewDidLoad()
let buttonTitles1 = ["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P"]
let buttonTitles2 = ["A", "S", "D", "F", "G", "H", "J", "K", "L"]
let buttonTitles3 = ["⬆︎", "Z", "X", "C", "V", "B", "N", "M", "⬅︎"]
let buttonTitles4 = ["123","🌐","⎯", "Return"]
//⚒
var row1 = createRowOfButtons(buttonTitles1)
var row2 = createRowOfButtons(buttonTitles2)
var row3 = createRowOfButtons(buttonTitles3)
var row4 = createRowOfButtons(buttonTitles4)
self.view.addSubview(row1)
self.view.addSubview(row2)
self.view.addSubview(row3)
self.view.addSubview(row4)
row1.setTranslatesAutoresizingMaskIntoConstraints(false)
row2.setTranslatesAutoresizingMaskIntoConstraints(false)
row3.setTranslatesAutoresizingMaskIntoConstraints(false)
row4.setTranslatesAutoresizingMaskIntoConstraints(false)
addConstraintsToInputView(self.view, rowViews: [row1, row2, row3, row4])
applyCurrentTheme()
//Normal keyboard end
//Change to numeric keyboard start
let buttonsNum1FirstRow = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
let buttonsNum2FirstRow = ["-", "/", ":", ";", "(", ")", "$", "&", "#", "\""]
let buttonsNum3FirstRow = ["#+=", ".", ",", "?", "!", "'", "7", "⬅︎"]
let buttonsNum4FirstRow = ["ABC","⎯","Return"]
//define rows as class variable instead of function variable
var Srow1:UIView!
var Srow2:UIView!
var Srow3:UIView!
var Srow4:UIView!
var Srow1Num:UIView!
//Hide it like below:
func didTapChangeToNumbersButton(sender: AnyObject?)
{
Srow1.hidden = true
Srow1Num.hidden = false
}
//Change to numeric keyboard end
}
func createRowOfButtons(buttonTitles: [NSString]) -> UIView
{
var buttons = [UIButton]()
var keyboardRowView = UIView(frame: CGRectMake(0, 0, 320, 50))
for buttonTitle in buttonTitles
{
let button = createButtonWithTitle(buttonTitle)
buttons.append(button)
keyboardRowView.addSubview(button)
}
allButtons += buttons
addIndividualButtonConstraints(buttons, mainView: keyboardRowView)
return keyboardRowView
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated
}
override func textWillChange(textInput: UITextInput)
{
// The app is about to change the document's contents. Perform any preparation here.
}
override func textDidChange(textInput: UITextInput)
{
// The app has just changed the document's contents, the document context has been updated.
var textColor: UIColor
var proxy = self.textDocumentProxy as UITextDocumentProxy
if proxy.keyboardAppearance == UIKeyboardAppearance.Dark
{
textColor = UIColor.whiteColor()
}
else
{
textColor = UIColor.blackColor()
}
}
func createButtonWithTitle(title: String) -> UIButton
{
let button = UIButton.buttonWithType(.System) as UIButton
button.frame = CGRectMake(0, 0, 20, 20)
button.setTitle(title, forState: .Normal)
button.sizeToFit()
button.titleLabel?.font = UIFont.systemFontOfSize(10)
button.setTranslatesAutoresizingMaskIntoConstraints(false)
button.backgroundColor = UIColor(white: 1.0, alpha: 1.0)
button.setTitleColor(UIColor.darkGrayColor(), forState: .Normal)
button.addTarget(self, action: "didTapButton:", forControlEvents: .TouchUpInside)
return button
}
func didTapButton(sender: AnyObject?)
{
let button = sender as UIButton
var proxy = textDocumentProxy as UITextDocumentProxy
let capon = false;
let capslast = false;
let capslock = false;
let spacelast = false;
if let title = button.titleForState(.Normal)
{
switch title
{
case "🌐" :
self.advanceToNextInputMode()
case "." :
let capon = true
proxy.insertText(".")
let spacelast = false
let capslast = false
//Caps idea
//this caps lock code is experimental and actually doesn't work, just an idea I was playing with
case "⬆︎" :
let capon = !capon
if capslock
{
let capon = true
let capslock = false
let capslast = false
}
let capslast = true
//Caps idea
case "⬅︎" :
proxy.deleteBackward()
let spacelast = false
let capslast = false
case "Return" :
proxy.insertText("\n")
let spacelast = false
let capslast = false
case "⎯" :
if spacelast
{
proxy.deleteBackward()
proxy.insertText(". ")
let spacelast = false
let capon = true
}
else
{
proxy.insertText(" ")
let spacelast = true
}
let capslast = false
default :
proxy.insertText(title)
}
}
}
func applyCurrentTheme()
{
var theme = ClaptonTheme()
theme.applyThemeToView(self.view)
theme.applyThemeToKeys(allButtons)
}
func addIndividualButtonConstraints(buttons: [UIButton], mainView: UIView)
{
for (index, button) in enumerate(buttons)
{
var topConstraint = NSLayoutConstraint(item: button, attribute: .Top, relatedBy: .Equal, toItem: mainView, attribute: .Top, multiplier: 1.0, constant: 1)
var bottomConstraint = NSLayoutConstraint(item: button, attribute: .Bottom, relatedBy: .Equal, toItem: mainView, attribute: .Bottom, multiplier: 1.0, constant: -1)
var rightConstraint : NSLayoutConstraint!
if index == buttons.count - 1
{
rightConstraint = NSLayoutConstraint(item: button, attribute: .Right, relatedBy: .Equal, toItem: mainView, attribute: .Right, multiplier: 1.0, constant: -1)
}
else
{
let nextButton = buttons[index+1]
rightConstraint = NSLayoutConstraint(item: button, attribute: .Right, relatedBy: .Equal, toItem: nextButton, attribute: .Left, multiplier: 1.0, constant: -1)
}
var leftConstraint : NSLayoutConstraint!
if index == 0 {
leftConstraint = NSLayoutConstraint(item: button, attribute: .Left, relatedBy: .Equal, toItem: mainView, attribute: .Left, multiplier: 1.0, constant: 1)
}
else
{
let prevtButton = buttons[index-1]
leftConstraint = NSLayoutConstraint(item: button, attribute: .Left, relatedBy: .Equal, toItem: prevtButton, attribute: .Right, multiplier: 1.0, constant: 1)
let firstButton = buttons[0]
var widthConstraint = NSLayoutConstraint(item: firstButton, attribute: .Width, relatedBy: .Equal, toItem: button, attribute: .Width, multiplier: 1.0, constant: 0)
widthConstraint.priority = 800
mainView.addConstraint(widthConstraint)
}
mainView.addConstraints([topConstraint, bottomConstraint, rightConstraint, leftConstraint])
}
}
func addConstraintsToInputView(inputView: UIView, rowViews: [UIView])
{
for (index, rowView) in enumerate(rowViews) {
var rightSideConstraint = NSLayoutConstraint(item: rowView, attribute: .Right, relatedBy: .Equal, toItem: inputView, attribute: .Right, multiplier: 1.0, constant: -1)
var leftConstraint = NSLayoutConstraint(item: rowView, attribute: .Left, relatedBy: .Equal, toItem: inputView, attribute: .Left, multiplier: 1.0, constant: 1)
inputView.addConstraints([leftConstraint, rightSideConstraint])
var topConstraint: NSLayoutConstraint
if index == 0
{
topConstraint = NSLayoutConstraint(item: rowView, attribute: .Top, relatedBy: .Equal, toItem: inputView, attribute: .Top, multiplier: 1.0, constant: 0)
}
else
{
let prevRow = rowViews[index-1]
topConstraint = NSLayoutConstraint(item: rowView, attribute: .Top, relatedBy: .Equal, toItem: prevRow, attribute: .Bottom, multiplier: 1.0, constant: 0)
let firstRow = rowViews[0]
var heightConstraint = NSLayoutConstraint(item: firstRow, attribute: .Height, relatedBy: .Equal, toItem: rowView, attribute: .Height, multiplier: 1.0, constant: 0)
heightConstraint.priority = 800
inputView.addConstraint(heightConstraint)
}
inputView.addConstraint(topConstraint)
var bottomConstraint: NSLayoutConstraint
if index == rowViews.count - 1
{
bottomConstraint = NSLayoutConstraint(item: rowView, attribute: .Bottom, relatedBy: .Equal, toItem: inputView, attribute: .Bottom, multiplier: 1.0, constant: 0)
}
else
{
let nextRow = rowViews[index+1]
bottomConstraint = NSLayoutConstraint(item: rowView, attribute: .Bottom, relatedBy: .Equal, toItem: nextRow, attribute: .Top, multiplier: 1.0, constant: 0)
}
inputView.addConstraint(bottomConstraint)
}
}
}

Resources