Programmatically add class to UIbutton in Swift - iphone

I'm new to Swift and am confused as how to programmatically add a custom class to a button. I created a custom class and can add it using the storyboard. It works fine, but how would this be done programmatically?
Can I use the CheckBox class in place of UIButton or would I still need to use UIButton and add the class?
The Class
class CheckBox: UIButton {
//images
let checkedImage = UIImage(named: "checked_checkbox") //as UIImage!
let uncheckedImage = UIImage(named: "unchecked_checkbox") //as UIImage!
//bool property
var isChecked:Bool = false{
didSet{
if isChecked == true {
self.setImage(checkedImage, forState: .Normal)
}else {
self.setImage(uncheckedImage, forState: .Normal)
}
}
}
override func awakeFromNib() {
self.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
self.isChecked = false
}
func buttonClicked(sender:UIButton) {
if(sender == self){
if isChecked == true {
println("setting to false")
isChecked = false
}else{
println("setting to true")
isChecked = true
}
}
}
}
Adding the class to the view controller
override func viewDidLoad() {
super.viewDidLoad()
let checkBox = CheckBox()
checkBox.backgroundColor = UIColor.blueColor()
self.view.addSubview(checkBox)
checkBox.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.addConstraint(NSLayoutConstraint(item: checkBox, attribute: .Left, relatedBy: .Equal, toItem: self.view, attribute: .Left, multiplier: 1.0, constant: 50))
self.view.addConstraint(NSLayoutConstraint(item: checkBox, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1.0, constant: 50))
}

the checkbox does not appear
Could that be because you have forgotten to give your checkbox any size?
Also, I notice you have these images:
let checkedImage = UIImage(named: "checked_checkbox") //as UIImage!
let uncheckedImage = UIImage(named: "unchecked_checkbox") //as UIImage!
But could it be that you have forgotten to put either of those images in the button? I don't see any code that does that.
If I call checkbox.isCheck = true or false the checkbox appears but does not change if clicked
Could that be because you have forgotten to give your checkbox any target-action for its control event? Previously you had this code:
override func awakeFromNib() {
self.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
self.isChecked = false
}
But now there is no awakeFromNib call - this button does not awake from a nib. The storyboard is the nib. This button is coming from code now.
If you fix that, so that that code is called, then isChecked will be set and the image will appear, won't it?

If you decide to do it programmatically(swift 2.2), and not via the storyboard, make sure you add an override int function, a required init? function, and put the following in your override init:
override init(frame: CGRect)
{
super.init(frame: frame)
self.addTarget(self, action: #selector(CheckBox.ButtonClicked(_:)),
forControlEvents: UIControlEvents.TouchUpInside)
self.isChecked = false
self.setImage(uncheckedImage, forState: .Normal)
}
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
The important bit is the self.setImage. I couldn't get the images to appear when the View loaded up.

Related

How can i manage both button of navigation bar when scrolling table with large navigation title?

here i can attached screenshots which i faced as an issue when scrolling at time i want to hide that more button or put that button into navigation bar as 2nd button but it's override to 1st one.
i set button into did load by calling simply this function.
func setUpNavigationMoreButton() {
let rightButton = UIButton()
let btnFilterImage = #imageLiteral(resourceName: "DotsThreeOutline")
rightButton.setImage(btnFilterImage, for: .normal)
rightButton.setTitleColor(.purple, for: .normal)
rightButton.addTarget(self, action: #selector(filterClick), for: .touchUpInside)
navigationController?.navigationBar.addSubview(rightButton)
rightButton.tag = 1
rightButton.frame = CGRect(x: self.view.frame.width, y: 0, width: 30, height: 30)
let targetView = self.navigationController?.navigationBar
let trailingContraint = NSLayoutConstraint(item: rightButton, attribute:
.trailingMargin, relatedBy: .equal, toItem: targetView,
attribute: .trailingMargin, multiplier: 1.0, constant: -16)
let bottomConstraint = NSLayoutConstraint(item: rightButton, attribute: .bottom, relatedBy: .equal,
toItem: targetView, attribute: .bottom, multiplier: 1.0, constant: -6)
rightButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([trailingContraint, bottomConstraint])
}
You have to use UIBarButtonItem instead of a UIButton.
let btnFilterImage = #imageLiteral(resourceName: "DotsThreeOutline")
let rightButton = UIBarButtonItem(image: btnFilterImage, style: .plain, target: self, action: #selector(filterClick))
navigationController?.navigationItem.rightBarButtonItem = rightButton
If you have multiple buttons
let rightButton1 = UIBarButtonItem(image: image1, style: .plain, target: self, action: #selector(filterClick))
let rightButton2 = UIBarButtonItem(image: image2, style: .plain, target: self, action: #selector(filterClick))
navigationController?.navigationItem.rightBarButtonItems = [rightButton1, rightButton2]
If you need to hide/unhide the more button when the Large title changes.
class VController: UIViewController {
let rightButton = UIButton()
var observer: NSKeyValueObservation?
override func viewDidLoad() {
super.viewDidLoad()
self.observer = self.navigationController?.navigationBar.observe(\.bounds, options: [.new], changeHandler: { (navigationBar, changes) in
if let height = changes.newValue?.height {
if height > 44.0 {
//Large Title, unhide button
rightButton.isHidden = false
} else {
//Small Title, hide button
rightButton.isHidden = true
}
}
})
}
}

UIView.animate works fine in viewDidAppear() but fires instantly anywhere else

I have looked and tried every solution I could find online as to why my animations is not properly firing. DISCLOSURE: they work fine when put in viewDidAppear(). This question has been asked countless times but none of the solutions work. The results of the animations appear but not with the delay specified, they are instant. What I would like is to fade in a my requestRideButton in and out using either isHidden with UIView.transition or alpha with UIView.animate.
I would also like to move the button while it is fading. I have tried every combination of self.view.layoutIfNeeded() both in and out the animate closure with the constraint in and out. I have also tried it with self.view.superview?.layoutIfNeeded()
class RideRequestViewController: UIViewController, MKMapViewDelegate {
#IBOutlet weak var rideRequestBottomButtonConstraint: NSLayoutConstraint!
#IBOutlet weak var rideRequestButtonTopConstraint: NSLayoutConstraint!
// Views
#IBOutlet var mapView: MKMapView!
#IBOutlet var rideDetailsView: UIView!
#IBOutlet var requestRideButton: UIButton!
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Layout map view to fill screen
mapView.frame = view.bounds
// Apply corner radius and shadow styling to floating views
let cornerRadius: CGFloat = 5.0
inputContainerView.layoutCornerRadiusAndShadow(cornerRadius: cornerRadius)
originButton.layoutCornerRadiusMask(corners: [.topLeft, .topRight], cornerRadius: cornerRadius)
paymentButton.layoutCornerRadiusMask(corners: .bottomLeft, cornerRadius: cornerRadius)
priceButton.layoutCornerRadiusMask(corners: .bottomRight, cornerRadius: cornerRadius)
rideDetailsView.layoutCornerRadiusAndShadow(cornerRadius: cornerRadius)
pilotView.layoutCornerRadiusMask(corners: [.topLeft, .bottomLeft], cornerRadius: cornerRadius)
vehicleView.layoutCornerRadiusMask(corners: [.topRight, .bottomRight], cornerRadius: cornerRadius)
requestRideButton.layoutCornerRadiusAndShadow(cornerRadius: cornerRadius)
}
override func viewDidLoad() {
ref = Database.database().reference()
}
func animate() {
self.rideRequestButtonTopConstraint.constant = -44
UIView.animate(withDuration: 1) {
self.view.layoutIfNeeded()
}
}
#IBAction
private func handleRequestRideButtonTapped() {
switch rideRequestState {
case .none:
// Update to requesting state
rideRequestState = .requesting
// Perform payment request
paymentContext.requestPayment()
case .requesting:
// Do nothing
// Show button
break
case .active:
// Complete the ride
completeActiveRide()
}
}
private func reloadRequestRideButton() {
guard originPlacemark != nil && destinationPlacemark != nil && paymentContext.selectedPaymentMethod != nil else {
// Show disabled state
requestRideButton.backgroundColor = .riderGrayColor
requestRideButton.setTitle("CONFIRM DELIVERY", for: .normal)
requestRideButton.setTitleColor(.black, for: .normal)
requestRideButton.setImage(nil, for: .normal)
requestRideButton.isEnabled = false
return
}
animate() // <--- view just disappears instantly instead
switch rideRequestState {
case .none:
// Show enabled state
requestRideButton.backgroundColor = .riderYellowColor
requestRideButton.setTitle("CONFIRM DELIVERY", for: .normal)
requestRideButton.setTitleColor(.black, for: .normal)
requestRideButton.setImage(nil, for: .normal)
requestRideButton.isEnabled = true
case .requesting:
// Show loading state
requestRideButton.backgroundColor = .riderYellowColor
requestRideButton.setTitle("...", for: .normal)
requestRideButton.setTitleColor(.white, for: .normal)
requestRideButton.setImage(nil, for: .normal)
requestRideButton.isEnabled = false
case .active:
// Show completion state
requestRideButton.backgroundColor = .white
requestRideButton.setTitle("Complete Ride", for: .normal)
requestRideButton.setTitleColor(.riderDarkBlueColor, for: .normal)
requestRideButton.setImage(nil, for: .normal)
requestRideButton.isEnabled = true
}
}
Changes to views to be animated should be inside the animate block.
func animate() {
UIView.animate(withDuration: 1) {
self.rideRequestButtonTopConstraint.constant = -44
self.view.layoutIfNeeded()
}
}
Changing the constraint in the line above will just update a value and move the view. It won't animate it
UPDATE
So based on looking at another answer and some additional research, The author of UIKit suggests that we update constraints and call layoutIfNeeded inside the animation block like above.
Here is the playground I used to test it
import UIKit
import PlaygroundSupport
class ViewController: UIViewController {
let movableView = UIView()
var topConstraint: NSLayoutConstraint?
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
view.addSubview(button)
button.setTitle("Animate", for: .normal)
button.addTarget(self, action: #selector(animate), for: .touchUpInside)
view.addSubview(movableView)
movableView.backgroundColor = .red
movableView.translatesAutoresizingMaskIntoConstraints = false
topConstraint = NSLayoutConstraint(item: movableView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 100)
topConstraint?.isActive = true
NSLayoutConstraint(item: movableView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: movableView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 100).isActive = true
NSLayoutConstraint(item: movableView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 100).isActive = true
}
#objc func animate() {
UIView.animate(withDuration: 4.0, animations: {
self.topConstraint?.constant = -100
self.view.layoutIfNeeded()
})
}
}
let vc = ViewController()
PlaygroundPage.current.liveView = vc.view

AdMob implement (only code, no main storyboard)

I want put Ad banner in my app.
I don't have the storyboard, I 've 4 ViewCOntroller, in the main I've this, can someone help me please?
In AppDelegate: GADMobileAds.configure(withApplicationID: "...")
import UIKit
import Firebase
import GoogleMobileAds
class ViewController: UIViewController {
var window: UIWindow?
override func viewDidLoad(){
super.viewDidLoad()
self.title="Andrea Damante Quiz"
self.view.backgroundColor=UIColor(patternImage: UIImage(named: "andrea15.jpeg")!)
let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
backgroundImage.image = UIImage(named: "andrea15.jpeg")
backgroundImage.contentMode = UIViewContentMode.scaleAspectFill
self.view.insertSubview(backgroundImage, at: 0)
setupViews()
}
#objc func btnGetStartedAction() {
let v=QuizVC()
self.navigationController?.pushViewController(v, animated: true)
}
func setupViews() {
self.view.addSubview(lblTitle)
lblTitle.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 150).isActive=true
lblTitle.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive=true
lblTitle.widthAnchor.constraint(equalToConstant: 250).isActive=true
lblTitle.heightAnchor.constraint(equalToConstant: 80).isActive=true
self.view.addSubview(btnGetStarted)
btnGetStarted.heightAnchor.constraint(equalToConstant: 50).isActive=true
btnGetStarted.widthAnchor.constraint(equalToConstant: 150).isActive=true
btnGetStarted.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive=true
btnGetStarted.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: 0).isActive=true
}
let lblTitle: UILabel = {
let lbl=UILabel()
lbl.text="Quiz"
lbl.textColor=UIColor.darkGray
lbl.textAlignment = .center
lbl.font = UIFont.systemFont(ofSize: 46)
lbl.numberOfLines=2
lbl.translatesAutoresizingMaskIntoConstraints=false
return lbl
}()
let btnGetStarted: UIButton = {
let btn=UIButton()
btn.setTitle("Via!", for: .normal)
btn.setTitleColor(UIColor.white, for: .normal)
btn.backgroundColor=UIColor.orange
btn.layer.cornerRadius=5
btn.layer.masksToBounds=true
btn.translatesAutoresizingMaskIntoConstraints=false
btn.addTarget(self, action: #selector(btnGetStartedAction), for: .touchUpInside)
return btn
}()
}
You need to declare and set up a GADBannerView and add it to your view controller. You won't need a UIWindow. Use this code:
import GoogleMobileAds
import UIKit
class ViewController: UIViewController {
var bannerView: GADBannerView!
override func viewDidLoad() {
super.viewDidLoad()
// In this case, we instantiate the banner with desired ad size.
bannerView = GADBannerView(adSize: kGADAdSizeBanner)
addBannerViewToView(bannerView)
}
func addBannerViewToView(_ bannerView: GADBannerView) {
bannerView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(bannerView)
view.addConstraints(
[NSLayoutConstraint(item: bannerView,
attribute: .bottom,
relatedBy: .equal,
toItem: bottomLayoutGuide,
attribute: .top,
multiplier: 1,
constant: 0),
NSLayoutConstraint(item: bannerView,
attribute: .centerX,
relatedBy: .equal,
toItem: view,
attribute: .centerX,
multiplier: 1,
constant: 0)
])
}
}
which was taken from here: https://developers.google.com/admob/ios/banner.
Also make sure to set the ad unit ID and the delegate:
override func viewDidLoad() {
super.viewDidLoad()
...
bannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716"
bannerView.rootViewController = self
bannerView.load(GADRequest())
}
But again, you'll everything you need in the official guide.

Make UIImageView Clickable and Send To Website

I am making UIImageView instances. I am having trouble making the UIImage clickable. I also would like the UIImage when clicked to send the user to a link on the Internet. How can I accomplish this? I have tried adding tap gestures and such but am having no luck. You can see this with the code that is commented out.
/File 1 Model File/
import Foundation
class Book : NSObject{
var thumbnailImageName: String?
var title : String?
var subTitle : String?
}
/File 2 Cell File/
import UIKit
class BookCell: BaseCell{
var book: Book?{
didSet{
thumbnailImageView.image = UIImage(named: (book?.thumbnailImageName)!)
titleLabel.text = book?.title
subtitleTextView.text = book?.subTitle
}
}
var thumbnailImageView: UIImageView = {
let imageView = UIImageView()
// let tapGesture = UITapGestureRecognizer(target: imageView, action: #selector(BookCell.tapBlurButton(_:)))
imageView.image = UIImage(named: "")
imageView.userInteractionEnabled = true
imageView.tag = 0
imageView.contentMode = .ScaleAspectFit
imageView.clipsToBounds = true
// imageView.addTarget(self, action: #selector(self.tapBlurButton(_:)), forControlEvents: .TouchUpInside)
// imageView.addGestureRecognizer(tapGestureRecognizer)
return imageView
}()
let userProfileImageView: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "Gary Vee Profile Pic 1")
imageView.layer.cornerRadius = 22
imageView.layer.masksToBounds = true
return imageView
}()
let separatorView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(red: 230/255, green: 230/255, blue: 230/255, alpha: 1)
return view
}()
let titleLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "DailyVee 199"
label.userInteractionEnabled = false
return label
}()
let subtitleTextView: UITextView = {
let textView = UITextView()
textView.translatesAutoresizingMaskIntoConstraints = false
textView.text = "When a street hustler make 130 million"
textView.userInteractionEnabled = false
textView.textContainerInset = UIEdgeInsetsMake(0,-4,0,0)
textView.textColor = UIColor.darkGrayColor()
return textView
}()
let purchaseButton: UIButton = {
let button = UIButton(type: .System) // let preferred over var here
button.frame = CGRectMake(100, 100, 100, 50)
button.backgroundColor = UIColor.greenColor()
button.setTitle("Button", forState: UIControlState.Normal)
button.addTarget(button, action: #selector(Books.tapBlurButton(_:)), forControlEvents: .TouchUpInside)
return button
}()
override func setupViews(){
addSubview(thumbnailImageView)
addSubview(separatorView)
addSubview(userProfileImageView)
addSubview(titleLabel)
addSubview(subtitleTextView)
addSubview(purchaseButton)
addContraintsWithFormat("H:|-16-[v0]-16-|", views: thumbnailImageView)
addContraintsWithFormat("H:|-16-[v0(44)]", views: userProfileImageView)
//Vertical constraints
addContraintsWithFormat("V:|-16-[v0]-8-[v1(44)]-16-[v2(1)]|", views: thumbnailImageView, userProfileImageView, separatorView)
addContraintsWithFormat("H:|[v0]|", views: separatorView)
//top constraint
addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .Top, relatedBy: .Equal, toItem: thumbnailImageView, attribute:.Bottom, multiplier: 1, constant: 8))
//left constraint
addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .Left, relatedBy: .Equal, toItem: userProfileImageView, attribute:.Right, multiplier: 1, constant: 8))
//right constraint
addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .Right, relatedBy: .Equal, toItem: thumbnailImageView, attribute:.Right, multiplier: 1, constant: 0))
//height constraint
addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .Height, relatedBy: .Equal, toItem: self, attribute:.Height, multiplier: 0, constant: 20))
//top constraint
addConstraint(NSLayoutConstraint(item: subtitleTextView, attribute: .Top, relatedBy: .Equal, toItem: titleLabel, attribute:.Bottom, multiplier: 1, constant: 4))
//left constraint
addConstraint(NSLayoutConstraint(item: subtitleTextView, attribute: .Left, relatedBy: .Equal, toItem: userProfileImageView, attribute:.Right, multiplier: 1, constant: 8))
//right constraint
addConstraint(NSLayoutConstraint(item: subtitleTextView, attribute: .Right, relatedBy: .Equal, toItem: thumbnailImageView, attribute:.Right, multiplier: 1, constant: 0))
//height constraint
addConstraint(NSLayoutConstraint(item: subtitleTextView, attribute: .Height, relatedBy: .Equal, toItem: self, attribute:.Height, multiplier: 0, constant: 30))
}
}
/File 3 Class File/
class Books : UICollectionViewController, UICollectionViewDelegateFlowLayout {
var books: [Book] = {
var askGaryVee = Book()
askGaryVee.thumbnailImageName = "askgaryvee_book"
askGaryVee.title = "#ASKGARYVEE: ONE ENTREPRENEUR'S TAKE ON LEADERSHIP, SOCIAL MEDIA, AND SELF-AWARENESS"
askGaryVee.subTitle = "by Gary Vaynerchuk"
var jabJabJabRightHook = Book()
jabJabJabRightHook.thumbnailImageName = "jab_jab_jab_right_hook_book"
jabJabJabRightHook.title = "JAB, JAB, JAB, RIGHT HOOK: HOW TO TELL YOUR STORY IN A NOISY SOCIAL WORLD"
jabJabJabRightHook.subTitle = "by Gary Vaynerchuk"
var theThankYouEconomy = Book()
theThankYouEconomy.thumbnailImageName = "the_thank_you_economy_book"
theThankYouEconomy.title = "The Thank You Economy"
theThankYouEconomy.subTitle = "by Gary Vaynerchuk"
var crushIt = Book()
crushIt.thumbnailImageName = "cursh_it_book"
crushIt.title = "CRUSH IT! WHY NOW IS THE TIME TO CASH IN ON YOUR PASSION"
crushIt.subTitle = "by Gary Vaynerchuk"
return[askGaryVee, jabJabJabRightHook, theThankYouEconomy, crushIt]
}()
func tapBlurButton(sender: AnyObject) {
print("Please Help!")
}
override func viewDidLoad() {
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
navigationItem.title = "Books"
collectionView!.backgroundColor = UIColor.whiteColor()
collectionView?.registerClass(BookCell.self, forCellWithReuseIdentifier:"cellId")
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return books.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cellId", forIndexPath: indexPath) as! BookCell
cell.book = books[indexPath.item]
return cell
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let height = (view.frame.width - 16 - 16) * 9 / 16
return CGSizeMake(view.frame.width, height + 16 + 68)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 0
}
}
The easiest solution is to add a clear UIButton on top of your UIImageView and set the frame of your UIButton to be the same as your UIImageView. Then you can use the UIButton's IBAction to send the user to the link.
var tumbnailButton: UIButton = {
let button = UIButton(frame: thumbnailImageView.frame)
button.addTarget(self, action: #selector(tapBlurButton(_:)), for: .touchUpInside)
button.clipsToBounds = true
return button
}()
EDIT:
The above code might throw an error since it is a computed property. Try replacing
var tumbnailButton: UIButton = {
with
var tumbnailButton: UIButton {
and remove the parenthesis at the end.
If that doesn't work, try
var tumbnailButton: UIButton {
get{
let button = UIButton(frame: thumbnailImageView.frame)
button.addTarget(self, action: #selector(tapBlurButton(_:)), for: .touchUpInside)
button.clipsToBounds = true
return button
}
}
Make this class which inherits UITapGestureRecognizer
open class BlockTap: UITapGestureRecognizer {
fileprivate var tapAction: ((UITapGestureRecognizer) -> Void)?
public override init(target: Any?, action: Selector?) {
super.init(target: target, action: action)
}
public convenience init (
tapCount: Int = 1,
fingerCount: Int = 1,
action: ((UITapGestureRecognizer) -> Void)?) {
self.init()
self.numberOfTapsRequired = tapCount
#if os(iOS)
self.numberOfTouchesRequired = fingerCount
#endif
self.tapAction = action
self.addTarget(self, action: #selector(BlockTap.didTap(_:)))
}
open func didTap (_ tap: UITapGestureRecognizer) {
tapAction? (tap)
}
}
then make an extension of UIImageView or UIView
extension UIImageView {
public func addTapGesture(tapNumber: Int = 1, action: ((UITapGestureRecognizer) -> ())?) {
let tap = BlockTap(tapCount: tapNumber, fingerCount: 1, action: action)
addGestureRecognizer(tap)
isUserInteractionEnabled = true
}
}
Then You can use this as
imageView?.addTapGesture(action: {[unowned self] (_) in
//Do whatever on click of image
})
In Your code you can use this as
you can use addTapGesture to any imageview in your code like this
let userProfileImageView: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "Gary Vee Profile Pic 1")
imageView.layer.cornerRadius = 22
imageView.layer.masksToBounds = true
imageView?.addTapGesture(action: {[unowned self] (_) in
//Code you want to execute on click of Imageview
imageView?.cornerRadius = 4.0
imageView?.clipsToBounds = true
})
return imageView
}()
on click of imageView cornerRadius of image will change to 4.0.

How do I set Custom Keyboad as a default keyboard to UITextView?

I've created custom keyboard and it works fine. But I don't know how to set my custom keyboard to specific UITextField.
This is my KeyboardViewController
import UIKit
class KeyboardViewController: UIInputViewController {
#IBOutlet var nextKeyboardButton: UIButton!
#IBOutlet weak var percentView: UIView!
#IBOutlet weak var hideKeyboardButton: UIButton!
override func updateViewConstraints() {
super.updateViewConstraints()
// Add custom view sizing constraints here
}
override func viewDidLoad() {
super.viewDidLoad()
// Perform custom UI setup here
self.nextKeyboardButton = UIButton(type: .System)
self.nextKeyboardButton.setTitle(NSLocalizedString("Next Keyboard", comment: "Title for 'Next Keyboard' button"), forState: .Normal)
self.nextKeyboardButton.sizeToFit()
self.nextKeyboardButton.translatesAutoresizingMaskIntoConstraints = false
self.nextKeyboardButton.addTarget(self, action: "advanceToNextInputMode", forControlEvents: .TouchUpInside)
self.view.addSubview(self.nextKeyboardButton)
let nextKeyboardButtonLeftSideConstraint = NSLayoutConstraint(item: self.nextKeyboardButton, attribute: .Left, relatedBy: .Equal, toItem: self.view, attribute: .Left, multiplier: 1.0, constant: 0.0)
let nextKeyboardButtonBottomConstraint = NSLayoutConstraint(item: self.nextKeyboardButton, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 1.0, constant: 0.0)
self.view.addConstraints([nextKeyboardButtonLeftSideConstraint, nextKeyboardButtonBottomConstraint])
let nib = UINib(nibName: "KeyboardView", bundle: nil)
let objects = nib.instantiateWithOwner(self, options: nil)
view = objects[0] as! UIView;
for view in self.view.subviews {
if let btn = view as? UIButton {
btn.layer.cornerRadius = 5.0
btn.translatesAutoresizingMaskIntoConstraints = false
//btn.addTarget(self, action: "keyPressed:", forControlEvents: .TouchUpInside)
}
}
}
and other delegate methods. So how can I call this ?
Actually the problem is I couldn't import custom keyboard classes from app extension. That's the main problem. I did this all build phases stuff. And I can use the keyboard if I change keyboard myself.
According Apple Documentation
After a user chooses a custom keyboard, it becomes the keyboard for every app the user opens.
Therefor it's not like your app specific thing, it's more like different languages keyboards. As far as you can't specify some specific language keyboard for your UITextField or UITextView you can't specify your custom keyboard as well.
Are you sure that you need Custom Keyboard instead of custom view for data input inside your app? About custom data input views you can read here.