Swift Preserve UISwitch State on UILongPress - swift

I added in my project UILongPressGestureRecognizer on the UISwitch
class ViewController: UIViewController,UIGestureRecognizerDelegate {
var newSwitch:UISwitch!
func CreateSwitchWithIndex(index:Int) {
newSwitch = UISwitch()
newSwitch.tintColor = UIColor.blackColor()
newSwitch.tag = index+1;
newSwitch.addTarget(self, action: Selector("switchSen:"), forControlEvents: UIControlEvents.ValueChanged)
self.view.addSubview(newSwitch)
newSwitch.setOn(false, animated: true)
let newSwitchConstraintL = NSLayoutConstraint(item: newSwitch, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 50)
let newSwitchConstraintH = NSLayoutConstraint(item: newSwitch, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 50)
let coordX = 368
let coordY = 190
newSwitchConstraintX = NSLayoutConstraint(item: newSwitch, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 0, constant: CGFloat(coordX))
newSwitchConstraintY = NSLayoutConstraint(item: newSwitch, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 0, constant: CGFloat(coordY))
view.addConstraints([newSwitchConstraintX,newSwitchConstraintY,newSwitchConstraintH,newSwitchConstraintL])
var longPress = UILongPressGestureRecognizer(target: self, action: "menu:")
longPress.minimumPressDuration = 1
newSwitch .addGestureRecognizer(longPress)
longPress.delegate = self
}
func switchSen(sender:UISwitch!) {
if (sender.on == true){
println("on")
}
else{
println("off")
}
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
if(touch.view == newSwitch){
return false
}else{
return true
}
}
func menu(gesture:UILongPressGestureRecognizer) {
if(gesture.state == UIGestureRecognizerState.Began){
becomeFirstResponder()
var menu = UIMenuController.sharedMenuController()
var deleteItem = UIMenuItem(title: "Delete", action: Selector("delete"))
menu.menuItems = [deleteItem]
var lastLocation:CGPoint = gesture.locationInView(view)
menu.setTargetRect(CGRectMake(lastLocation.x, lastLocation.y, 0.0, 0.0), inView: view)
menu.setMenuVisible(true, animated: true)
}
}
func delete() {
println("Delete")
}
func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
func gestureRecognizer(UIGestureRecognizer,
shouldRecognizeSimultaneouslyWithGestureRecognizer:UIGestureRecognizer) -> Bool {
return true
}
I managed to get the delete menu when I press on the switch itself but now...
When I release the longpress my switch sets state the opposite of the initial state, so I think the shouldReceiveTouch don't go.
How can I preserve the status of my UISwitch ?

Related

Text Cursor out of view when typing

I have multiple PDFKit annotations added into my PDF Document. When the user selects the text annotations to add text, the keyboard appears and the document scrolls upward and the cursor is no long on the screen. I have tried treating the PDF Document as a textfield but that does not work. How can I keep the cursor on screen or centered above the keyboard when the user adds text on the PDF Annotation?
Here is my code:
import UIKit
import PDFKit
class PDFfun: UIViewController {
var pdfView = PDFView()
var textFieldMultiline3 = PDFAnnotation()
let document = PDFDocument(url: Bundle.main.url(forResource: "DOCUMENT", withExtension: "pdf")!)
override func viewDidLoad() {
super.viewDidLoad()
pdfView = PDFView(frame: self.view.frame)
pdfView.document = document
pdfView.autoScales = true
pdfView.backgroundColor = UIColor.lightGray
self.insertMultilineTextBoxIntoOneOneNine(document!.page(at: 119)!)
pdfView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(pdfView)
view.addConstraints([
NSLayoutConstraint(item: pdfView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0),
NSLayoutConstraint(item: pdfView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0),
NSLayoutConstraint(item: pdfView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0),
NSLayoutConstraint(item: pdfView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0)
])
}
func insertMultilineTextBoxIntoOneOneNine(_ page: PDFPage) {
_ = page.bounds(for: .cropBox)
let textFieldMultilineBounds3 = CGRect(x: 27, y: 50, width: 339, height: 510)
textFieldMultiline3 = PDFAnnotation(bounds: textFieldMultilineBounds3, forType: PDFAnnotationSubtype(rawValue: PDFAnnotationSubtype.widget.rawValue), withProperties: nil)
textFieldMultiline3.widgetFieldType = PDFAnnotationWidgetSubtype(rawValue: PDFAnnotationWidgetSubtype.text.rawValue)
textFieldMultiline3.backgroundColor = UIColor.white.withAlphaComponent(1)
textFieldMultiline3.font = UIFont(name: "Arial", size: 15)
textFieldMultiline3.isMultiline = true
page.addAnnotation(textFieldMultiline3)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
if UIDevice.current.orientation.isLandscape {
print("landscape")
pdfView = PDFView(frame: view.frame)
pdfView.autoScales = true
} else {
print("portait")
pdfView = PDFView(frame: view.frame)
pdfView.autoScales = true
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
pdfView.frame = view.frame
}
override var prefersStatusBarHidden: Bool {
return false
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}

App window on top of all windows including others app windows

I like to have my NSWindow top of everything including other app windows. How this is possible?
This is how my custom NSWindow looks like?
override init(contentRect: NSRect, styleMask style: NSWindow.StyleMask,
backing backingStoreType: NSWindow.BackingStoreType, defer flag: Bool) {
super.init(contentRect: contentRect, styleMask: NSWindow.StyleMask.borderless,
backing: NSWindow.BackingStoreType.buffered, defer: false)
// Manage window appearance and size
// this window manages video view controller
self.backgroundColor = NSColor.clear
self.alphaValue = CGFloat(AppSingleton.shared.getVideoOpacity()) / 100
self.isOpaque = false
self.collectionBehavior = .transient
}
And this how I open the NSWindowController from a button action
func openPlayerWindow(url: URL) {
let storyboard:NSStoryboard? = NSStoryboard(name: NSStoryboard.Name("Main"), bundle: Bundle.main)
let playerWindowController = storyboard?.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "SIPlayerWindowController")) as! PlayerWindowController
if let playerWindow = playerWindowController.window {
playerWindowController.showWindow(nil)
playerWindow.makeKeyAndOrderFront(self)
NSApp.activate(ignoringOtherApps: true)
let videoPlayerController = playerWindow.contentViewController as! VideoPlayerViewController
videoPlayerController.videoFile = url
}
}
PlayerView.swift
import Cocoa
import AVFoundation
class PlayerView: NSView {
override func hitTest(_ point: NSPoint) -> NSView? {
return nil;
}
}
This PlayerView immediately fill with CorePlayer in this func.
VideoViewController.swift
func playVideo(videoFile: URL) {
corePlayer.view().translatesAutoresizingMaskIntoConstraints = false
view.addSubview(corePlayer.view())
NSLayoutConstraint.init(item: corePlayer.view(), attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint.init(item: corePlayer.view(), attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint.init(item: corePlayer.view(), attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint.init(item: corePlayer.view(), attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0).isActive = true
corePlayer.playURL(videoFile.absoluteURL)
}
Try to use this
self.windowController?.showWindow(nil)
self.makeKeyAndOrderFront(self)
NSApp.activate(ignoringOtherApps: true)
I found the solution
self.ignoresMouseEvents = true;

UICollectionViewFlowLayout issues with collectionview and textfields

I have an app that uses a collectionview that scrolls horizontally, and has collectionviewcells inside of it. Everything was going fine until I tried to implement a login/register cell with 2 textfields in it using textfielddelegate. When I press on one of the textfields, the keyboard shows for a split second and then hides. After it does this, the view is pushed down a little bit and if I press the textfield again, it is pushed up and wont come down. Here are some screenshots of what it looks like:
before touching a textfield vs. after I touch a textfield
I get various UICollectionViewFlowLayout errors that call for me to make a symbolic breakpoint at UICollectionViewFlowLayoutBreakForInvalidSizes.
The behavior of the UICollectionViewFlowLayout is not defined because:
2017-04-26 13:55:03.199199-0400 Eyetube[1500:243622] the item height must be less than the height of the UICollectionView minus the section insets top and bottom values, minus the content insets top and bottom values.
2017-04-26 13:55:03.200490-0400 Eyetube[1500:243622] The relevant UICollectionViewFlowLayout instance is <UICollectionViewFlowLayout: 0x10453ee90>, and it is attached to <UICollectionView: 0x104806800; frame = (0 0; 768 960); clipsToBounds = YES; autoresize = W+H; gestureRecognizers = <NSArray: 0x17405a610>; layer = <CALayer: 0x17002f0a0>; contentOffset: {2304, 0}; contentSize: {3072, 910}> collection view layout: <UICollectionViewFlowLayout: 0x10453ee90>.
2017-04-26 13:55:03.200575-0400 Eyetube[1500:243622] Make a symbolic breakpoint at UICollectionViewFlowLayoutBreakForInvalidSizes to catch this in the debugger.
I tried debugging this multiple times, but it isn't too helpful in finding where exactly the error is coming from. I've been stuck on this issue for hours and can't seem to figure it out.
Where I initialize my layout in my collectionviewcontroller:
func setupCollectionView() {
if let flowLayout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.scrollDirection = .horizontal
flowLayout.minimumLineSpacing = 0
}
collectionView?.backgroundColor = UIColor.white
collectionView?.register(VideoFeedCell.self, forCellWithReuseIdentifier: cellId)
collectionView?.register(ChannelFeedCell.self, forCellWithReuseIdentifier: channelCellId)
collectionView?.register(ARFeedCell.self, forCellWithReuseIdentifier: augmentedRealityCellId)
collectionView?.register(LoginRegisterCell.self, forCellWithReuseIdentifier: loginRegisterCellId)
collectionView?.contentInset = UIEdgeInsetsMake(0, 0, 50, 0)
collectionView?.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 50, 0)
collectionView?.isPagingEnabled = true
}
My sizeForItemAt func, also in my collectionviewcontroller (P.S., I am subtracting 50 from the height because of the bottom menubar I have added as a subview of the view. I also changed the collectionview's contentInset and scrollIndicatorInsets because of this):
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cellSize = CGSize(width: view.frame.width, height: view.frame.height - 50)
return cellSize
}
Here is the complete code of the collectionviewcell, where I am having the issues:
import UIKit
class LoginRegisterCell: BaseCell, UITextFieldDelegate {
let logoImageView: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "eyetube_logo_font")
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
return imageView
}()
let emailTextField: LeftPaddedTextField = {
let tf = LeftPaddedTextField()
tf.keyboardType = .emailAddress
tf.placeholder = "Enter email"
tf.substituteFontName = "SourceSansPro-Regular"
tf.layer.borderColor = UIColor.rgb(220, green: 220, blue: 220).cgColor
tf.layer.borderWidth = 1
tf.translatesAutoresizingMaskIntoConstraints = false
return tf
}()
let passwordTextField: LeftPaddedTextField = {
let tf = LeftPaddedTextField()
tf.placeholder = "Enter password"
tf.substituteFontName = "SourceSansPro-Regular"
tf.layer.borderColor = UIColor.rgb(220, green: 220, blue: 220).cgColor
tf.layer.borderWidth = 1
tf.isSecureTextEntry = true
tf.translatesAutoresizingMaskIntoConstraints = false
return tf
}()
lazy var loginButton: UIButton = {
let button = UIButton(type: .system)
button.backgroundColor = UIColor.rgb(225, green: 31, blue: 40)
button.titleLabel?.font = UIFont(name: "SourceSansPro-SemiBold", size: 20)
button.setTitle("Log In", for: .normal)
button.setTitleColor(UIColor.white, for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(self, action: #selector(handleLogin), for: .touchUpInside)
return button
}()
lazy var registerLink: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Don't have an account? Register here", for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.titleLabel?.font = UIFont(name: "SourceSansPro-Regular", size: 18)
button.setTitleColor(UIColor.darkGray, for: .normal)
let underlineAttribute = [NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue]
let underlineAttributedString = NSAttributedString(string: (button.titleLabel?.text)!, attributes: underlineAttribute)
button.titleLabel?.attributedText = underlineAttributedString
button.addTarget(self, action: #selector(handleRegister), for: .touchUpInside)
return button
}()
var containerView: UIView!
override func setupViews() {
super.setupViews()
self.emailTextField.delegate = self
emailTextField.returnKeyType = .next
self.passwordTextField.delegate = self
passwordTextField.returnKeyType = .done
containerView = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height))
containerView.backgroundColor = .green
addSubview(containerView)
containerView.addSubview(logoImageView)
containerView.addSubview(emailTextField)
containerView.addSubview(passwordTextField)
containerView.addSubview(loginButton)
containerView.addSubview(registerLink)
setupLogoImageView()
setupInputs()
setupLoginButton()
setupRegisterLink()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func handleLogin() {
//first check if the email/password textfields are empty or not
guard let email = emailTextField.text , !email.isEmpty else {
let alert = UIAlertView (title: "Invalid Email", message: "Please enter an email to log in", delegate: self, cancelButtonTitle: "OK")
alert.show()
return
}
guard let password = passwordTextField.text , !password.isEmpty else {
let alert = UIAlertView (title: "Invalid Password", message: "Please enter a password to log in", delegate: self, cancelButtonTitle: "OK")
alert.show()
return
}
//create session here
ApiLoginAuthentication.sharedInstance.login_now(username: email, password: password, onCompletion: {(loginSuccessful: Bool) -> Void in
guard (loginSuccessful) else {
DispatchQueue.main.async {
let alert = UIAlertView (title: "Invalid Account info", message: "The account information entered is invalid. Please log in with a valid account.", delegate: self, cancelButtonTitle: "OK")
alert.show()
}
return
}
DispatchQueue.main.async {
self.emailTextField.text = ""
self.passwordTextField.text = ""
}
print("the login was successful")
})
/**
let profileUrl: String = "https://eyetube.net/user/profile.asp"
ApiLoginAuthentication.sharedInstance.getContent(contentUrl: profileUrl, onCompletion: {(responseString: String, isLoggedIn: Bool) -> Void in
print(responseString)
print("user status: \(isLoggedIn)")
let json: Any?
do {
let data: NSData = responseString.data(using: String.Encoding.utf8)! as NSData
json = try JSONSerialization.jsonObject(with: data as Data, options: .allowFragments)
print(json)
} catch let error {
print("error: \(error)")
}
})**/
}
func handleRegister() {
let eyetubeRegisterLink = "https://eyetube.net/user/register.asp?rUrl="
UIApplication.shared.openURL(URL(string: eyetubeRegisterLink)!)
}
func setupLogoImageView() {
var sizeConstant: CGFloat!
var centerYConstant: CGFloat!
if UI_USER_INTERFACE_IDIOM() == .pad {
sizeConstant = 400
centerYConstant = -260
} else {
sizeConstant = 200
centerYConstant = -160
}
NSLayoutConstraint(item: logoImageView, attribute: .centerY, relatedBy: .equal, toItem: containerView, attribute: .centerY, multiplier: 1, constant: centerYConstant!).isActive = true
NSLayoutConstraint(item: logoImageView, attribute: .centerX, relatedBy: .equal, toItem: containerView, attribute: .centerX, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: logoImageView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: sizeConstant).isActive = true
NSLayoutConstraint(item: logoImageView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: sizeConstant).isActive = true
}
func setupInputs() {
var widthConstant: CGFloat!
var leftConstant: CGFloat!
if UI_USER_INTERFACE_IDIOM() == .pad {
widthConstant = -64
leftConstant = 32
} else {
widthConstant = -32
leftConstant = 16
}
NSLayoutConstraint(item: emailTextField, attribute: .top, relatedBy: .equal, toItem: logoImageView, attribute: .bottom, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: emailTextField, attribute: .left, relatedBy: .equal, toItem: containerView, attribute: .left, multiplier: 1, constant: leftConstant).isActive = true
NSLayoutConstraint(item: emailTextField, attribute: .width, relatedBy: .equal, toItem: containerView, attribute: .width, multiplier: 1, constant: widthConstant).isActive = true
NSLayoutConstraint(item: emailTextField, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 50).isActive = true
NSLayoutConstraint(item: passwordTextField, attribute: .top, relatedBy: .equal, toItem: emailTextField, attribute: .bottom, multiplier: 1, constant: 8).isActive = true
NSLayoutConstraint(item: passwordTextField, attribute: .left, relatedBy: .equal, toItem: containerView, attribute: .left, multiplier: 1, constant: leftConstant).isActive = true
NSLayoutConstraint(item: passwordTextField, attribute: .width, relatedBy: .equal, toItem: containerView, attribute: .width, multiplier: 1, constant: widthConstant).isActive = true
NSLayoutConstraint(item: passwordTextField, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 50).isActive = true
}
func setupLoginButton() {
NSLayoutConstraint(item: loginButton, attribute: .centerX, relatedBy: .equal, toItem: containerView, attribute: .centerX, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: loginButton, attribute: .top, relatedBy: .equal, toItem: passwordTextField, attribute: .bottom, multiplier: 1, constant: 16).isActive = true
NSLayoutConstraint(item: loginButton, attribute: .width, relatedBy: .equal, toItem: passwordTextField, attribute: .width, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: loginButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 50).isActive = true
}
func setupRegisterLink() {
NSLayoutConstraint(item: registerLink, attribute: .centerX, relatedBy: .equal, toItem: containerView, attribute: .centerX, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: registerLink, attribute: .top, relatedBy: .equal, toItem: loginButton, attribute: .bottom, multiplier: 1, constant: 12).isActive = true
NSLayoutConstraint(item: registerLink, attribute: .width, relatedBy: .equal, toItem: loginButton, attribute: .width, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: registerLink, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 40).isActive = true
}
}

Autolayout constraints set in code not appearing in interface builder

I have a custom view that is set in interface builder with top, leading, trailing, height constraints.
In my Custom view i have a title and a button.
Im trying to add to the title a bottom and centerY constraints.
and to the button width, height, bottom, leading constraints.
When i add any constraint i get an warning in interface builder:
Expected: width=600, height=68.
Actual: width=0, height=0
When i run the code everything works, but i cant see anything in interface builder.
code:
#IBDesignable
class UIHeader: UIView {
var delegate: HeaderDelegate?
private lazy var titleLable: UILabel = {
let lbl = UILabel()
lbl.translatesAutoresizingMaskIntoConstraints = false
lbl.font = UIFont(name: "Lato-Light", size: 16)
lbl.text = "Title"
return lbl
}()
private lazy var backButton: UIButton = {
let btn = UIButton()
btn.tintColor = UIColor.lightGrayColor()
btn.translatesAutoresizingMaskIntoConstraints = false
let image = UIImage(named: "prev")
if let image = image {
btn.setImage(image.imageWithRenderingMode(.AlwaysTemplate), forState: .Normal)
}
btn.addTarget(self, action: #selector(UIHeader.OnBackButtonClickLister(_:)), forControlEvents: .TouchUpInside)
return btn
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
}
extension UIHeader {
#IBInspectable
var backButtonImage: UIImage? {
get {
return backButton.imageForState(.Normal)
}
set (newImage) {
backButton.setImage(newImage?.imageWithRenderingMode(.AlwaysTemplate), forState: .Normal)
}
}
#IBInspectable
var title: String? {
get {
return titleLable.text
}
set (newTitle) {
titleLable.text = newTitle
}
}
}
extension UIHeader {
private func setupView() {
backgroundColor = UIColor.whiteColor()
translatesAutoresizingMaskIntoConstraints = false
addSubview(titleLable)
addSubview(backButton)
//add shadow
layer.shadowColor = UIColor(white: 115/255, alpha: 1.0).CGColor
layer.shadowOpacity = 0.5
layer.shadowRadius = 8
layer.shadowOffset = CGSizeMake(0, -1)
NSLayoutConstraint.activateConstraints([
//Title//
//center x
NSLayoutConstraint(item: titleLable, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1.0, constant: 0),
//bottom
NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .Equal, toItem: titleLable, attribute: .Bottom, multiplier: 1, constant: 12),
//button//
//bottom
NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .Equal, toItem: backButton, attribute: .Bottom, multiplier: 1, constant: 4),
//leading
NSLayoutConstraint(item: backButton, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1, constant: 0),
//width
NSLayoutConstraint(item: backButton, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1, constant: 40),
//height
NSLayoutConstraint(item: backButton, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1, constant: 40)
])
}
}
I also tried to add the constraints with:
addConstraint(NSLayoutConstraint)
cant figure out what is the problem.
Thanks
I removed
translatesAutoresizingMaskIntoConstraints = false
and everything works great.

Swift How to add the shouldReceiveTouch on Switch?

I'm trying to add in my project shouldReceiveTouch on the UISwitch but i have a error
class ViewController: UIViewController,UIGestureRecognizerDelegate {
var newSwitch: UISwitch!
var deleteButtonIndex:Int!
var deleteSwitchIndex:Int!
let gesture = UILongPressGestureRecognizer()
func CreateSwitchWithIndex(index:Int) {
let newSwitch = UISwitch()
newSwitch.tintColor = UIColor.blackColor()
newSwitch.on = false
newSwitch.tag = index+1;
newSwitch.addTarget(self, action: Selector("switchSen:"), forControlEvents: UIControlEvents.ValueChanged)
self.view.addSubview(newSwitch)
newSwitch.setOn(false, animated: true)
let newSwitchConstraintL = NSLayoutConstraint(item: newSwitch, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 50)
let newSwitchConstraintH = NSLayoutConstraint(item: newSwitch, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 50)
let coordX = 368
let coordY = 190
newSwitchConstraintX = NSLayoutConstraint(item: newSwitch, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 0, constant: CGFloat(coordX))
newSwitchConstraintY = NSLayoutConstraint(item: newSwitch, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 0, constant: CGFloat(coordY))
view.addConstraints([newSwitchConstraintX,newSwitchConstraintY,newSwitchConstraintH,newSwitchConstraintL])
var longPress = UILongPressGestureRecognizer(target: self, action: "menu:")
longPress.minimumPressDuration = 1
longPress.delegate = self
newSwitch .addGestureRecognizer(longPress)
}
func switchSen(sender:UISwitch!) {
if (sender.on == true){
println("on")
}
else{
println("off")
}
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
if(touch.view == newSwitch){
return false
}else{
return true
}
}
func menu(gesture:UILongPressGestureRecognizer) {
if(gesture.state == UIGestureRecognizerState.Began){
self.deleteButtonIndex = gesture.view?.tag
self.deleteSwichIndex = gesture.view?.tag
becomeFirstResponder()
var menu = UIMenuController.sharedMenuController()
var deleteItem = UIMenuItem(title: "Delete", action: Selector("delete"))
menu.menuItems = [deleteItem]
var lastLocation:CGPoint = gesture.locationInView(view)
menu.setTargetRect(CGRectMake(lastLocation.x, lastLocation.y, 0.0, 0.0), inView: view)
menu.setMenuVisible(true, animated: true)
}
}
func delete(){
println("Delete")
}
}
I just get this error : fatal error: unexpectedly found nil while unwrapping an Optional value on if(touch.view == newSwitch)
How to add the shouldReceiveTouch on Switch ?
Please try to use this line
let newSwitch: UISwitch!
instead of
var newSwitch: UISwitch!