IOS开发—Using UIGestureRecognizer with Swift Tutoria

Update note: This tutorial was fully updated for iOS 8 and Swift by Caroline Begbie. Original post by Ray Wenderlich.

Update 12/10/14: Updated for Xcode 6.1.1.

If you need to detect gestures in your app, such as taps, pinches, pans, or rotations, it’s extremely easy with Swift and the built-in UIGestureRecognizer classes.

In this tutorial, you’ll learn how you can easily add gesture recognizers into your app, both within the Storyboard editor in Xcode, and programatically. You’ll create a simple app where you can move a monkey and a banana around by dragging, pinching, and rotating with the help of gesture recognizers.

You’ll also try out some cool extras like:

  • Adding deceleration for movement
  • Setting dependencies between gesture recognizers
  • Creating a custom UIGestureRecognizer so you can tickle the monkey!

This tutorial assumes you are familiar with the basic concepts of Storyboards. If you are new to them, you may wish to check out our Storyboard tutorials first.

I think the monkey just gave us the thumbs up gesture, so let’s get started! :]

Note: At the time of writing this tutorial, our understanding is we cannot post screenshots of Xcode 6 since it is still in beta. Therefore, we are suppressing screenshots in this Swift tutorial until we are sure it is OK.

Getting Started

Open up Xcode 6 and create a new project with the iOS\Application\Single View Application template. For the Product Name enter MonkeyPinch, for the Language choose Swift, and for the Devices choose iPhone. Click Next, choose the folder to save your project, and click Create.

Before you go any further, download the resources for this project and drag the six files into your project. Tick Destination: Copy items if needed, choose Create groups, and click Finish.

Next, open up Main.storyboard. View controllers are now square by default, so that you can use just one storyboard for multiple devices. Generally you will layout your storyboards using constraints and size classes. But because this app is only going to be for the iPhone, you can disable size classes. On the File Inspector panel (View Menu > Utilities > Show File Inspector), untick Use Size Classes. Choose Keep size class data for: iPhone, and click Disable Size Classes.

Your view will now reflect the size and proportions of the iPhone 5.

Drag an Image View into the View Controller. Set the image to monkey.png, and resize the Image View to match the size of the image itself by selecting Editor Menu > Size to Fit Content. Then drag a second image view in, set it to banana.png, and also resize it. Arrange the image views however you like in the view controller. At this point you should have something like this:

Arrange the image views within the view.

That’s it for the UI for this app – now you’ll add a gesture recognizer so you can drag those image views around!

UIGestureRecognizer Overview

Before you get started, here’s a brief overview of how you use UIGestureRecognizers and why they’re so handy.

In the old days before UIGestureRecognizers, if you wanted to detect a gesture such as a swipe, you’d have to register for notifications on every touch within a UIView – such as touchesBegan, touchesMoves, and touchesEnded. Each programmer wrote slightly different code to detect touches, resulting in subtle bugs and inconsistencies across apps.

In iOS 3.0, Apple came to the rescue with UIGestureRecognizer classes! These provide a default implementation of detecting common gestures such as taps, pinches, rotations, swipes, pans, and long presses. By using them, not only does it save you a ton of code, but it makes your apps work properly too! Of course you can still use the old touch notifications instead, if your app requires them.

Using UIGestureRecognizers is extremely simple. You just perform the following steps:

  1. Create a gesture recognizer. When you create a gesture recognizer, you specify a callback function so the gesture recognizer can send you updates when the gesture starts, changes, or ends.
  2. Add the gesture recognizer to a view. Each gesture recognizer is associated with one (and only one) view. When a touch occurs within the bounds of that view, the gesture recognizer will look to see if it matches the type of touch it’s looking for, and if a match is found it will notify the callback function.

You can perform these two steps programatically (which you’ll do later on in this tutorial), but it’s even easier adding a gesture recognizer visually with the Storyboard editor. So now to add your first gesture recognizer into this project!

UIPanGestureRecognizer

Still with Main.storyboard open, look inside the Object Library for the Pan Gesture Recognizer, and drag it on top of the monkey Image View. This both creates the pan gesture recognizer, and associates it with the monkey Image View. You can verify you got it connected OK by clicking on the monkey Image View, looking at the Connections Inspector (View Menu > Utilities > Show Connections Inspector), and making sure the Pan Gesture Recognizer is in the gestureRecognizers Outlet Collection.

You may wonder why you associated it to the image view instead of the view itself. Either approach would be OK, it’s just what makes most sense for your project. Since you tied it to the monkey, you know that any touches are within the bounds of the monkey so you’re good to go. The drawback of this method is sometimes you might want touches to be able to extend beyond the bounds. In that case, you could add the gesture recognizer to the view itself, but you’d have to write code to check if the user is touching within the bounds of the monkey or the banana and react accordingly.

Now that you’ve created the pan gesture recognizer and associated it to the image view, you just have to write the callback function so something actually happens when the pan occurs.

Open up ViewController.swift and add the following function at the end of the ViewController class:

@IBAction func handlePan(recognizer:UIPanGestureRecognizer) {
  let translation = recognizer.translationInView(self.view)
  recognizer.view!.center = CGPoint(x:recognizer.view!.center.x + translation.x,
                                    y:recognizer.view!.center.y + translation.y)
  recognizer.setTranslation(CGPointZero, inView: self.view)
}

The UIPanGestureRecognizer will call this function when a pan gesture is first detected, and then continuously as the user continues to pan, and one last time when the pan is complete (usually the user lifting their finger).

The UIPanGestureRecognizer passes itself as an argument to this function. You can retrieve the amount the user has moved their finger by calling the translationInView: function. Here you use that amount to move the center of the monkey the same amount the finger has been dragged.

It’s extremely important to set the translation back to zero once you are done. Otherwise, the translation will keep compounding each time, and you’ll see your monkey rapidly move off the screen!

Note that instead of hard-coding the monkey image view into this function, you get a reference to the monkey image view by calling recognizer.view. This makes your code more generic, so that you can re-use this same routine for the banana image view later on.

OK, now that this function is complete, you will hook it up to the UIPanGestureRecognizer. In Main.storyboard, control drag from the Pan Gesture Recognizer to View Controller. A popup will appear – select handlePan:.

One more thing. If you compile and run, and try to drag the monkey, it will not work yet. The reason is that touches are disabled by default on views that normally don’t accept touches, like Image Views. So select both image views, open up the Attributes Inspector, and check the User Interaction Enabled checkbox.

Compile and run again, and this time you should be able to drag the monkey around the screen!

Note that you can’t drag the banana. This is because gesture recognizers should be tied to one (and only one) view. So go ahead and add another gesture recognizer for the banana, by performing the following steps:

  1. Drag a Pan Gesture Recognizer on top of the banana Image View.
  2. Control drag from the new Pan Gesture Recognizer to the View Controller and connect it to the handlePan: function.

Give it a try and you should now be able to drag both image views across the screen. Pretty easy to implement such a cool and fun effect, eh?

Gratuitous Deceleration

In a lot of Apple apps and controls, when you stop moving something there’s a bit of deceleration as it finishes moving. Think about scrolling a web view, for example. It’s common to want to have this type of behavior in your apps.

There are many ways of doing this, but you’re going to do one very simple implementation for a rough but nice effect. The idea is to detect when the gesture ends, figure out how fast the touch was moving, and animate the object moving to a final destination based on the touch speed.

  • To detect when the gesture ends: The callback passed to the gesture recognizer is called potentially multiple times – when the gesture recognizer changes its state to began, changed, or ended for example. You can find out what state the gesture recognizer is in simply by looking at its state property.
  • To detect the touch velocity: Some gesture recognizers return additional information – you can look at the API guide to see what you can get. There’s a handy function called velocityInView that you can use in the UIPanGestureRecognizer!

So add the following to the bottom of the handlePan: function in ViewController.swift:

if recognizer.state == UIGestureRecognizerState.Ended {
  // 1
  let velocity = recognizer.velocityInView(self.view)
  let magnitude = sqrt((velocity.x * velocity.x) + (velocity.y * velocity.y))
  let slideMultiplier = magnitude / 200
  println("magnitude: \(magnitude), slideMultiplier: \(slideMultiplier)")

  // 2
  let slideFactor = 0.1 * slideMultiplier     //Increase for more of a slide
  // 3
  var finalPoint = CGPoint(x:recognizer.view!.center.x + (velocity.x * slideFactor),
                           y:recognizer.view!.center.y + (velocity.y * slideFactor))
  // 4
  finalPoint.x = min(max(finalPoint.x, 0), self.view.bounds.size.width)
  finalPoint.y = min(max(finalPoint.y, 0), self.view.bounds.size.height)

  // 5
  UIView.animateWithDuration(Double(slideFactor * 2),
                             delay: 0,
                             // 6
                             options: UIViewAnimationOptions.CurveEaseOut,
                             animations: {recognizer.view!.center = finalPoint },
                             completion: nil)
}

This is just a very simple function I wrote up for this tutorial to simulate deceleration. It takes the following strategy:

  1. Figure out the length of the velocity vector (i.e. the magnitude)
  2. If the length is < 200, then decrease the base speed, otherwise increase it.
  3. Calculate a final point based on the velocity and the slideFactor.
  4. Make sure the final point is within the view’s bounds
  5. Animate the view to the final resting place.
  6. Use the “ease out” animation option to slow down the movement over time.

Compile and run to try it out, you should now have some basic but nice deceleration! Feel free to play around with it and improve it – if you come up with a better implementation, please share in the forum discussion at the end of this article.

Pinch and Rotation Gestures

Your app is coming along great so far, but it would be even cooler if you could scale and rotate the image views by using pinch and rotation gestures as well!

First, add the code for the callbacks. Add the following functions to ViewController.swift at the end of the ViewController class:

@IBAction func handlePinch(recognizer : UIPinchGestureRecognizer) {
  recognizer.view!.transform = CGAffineTransformScale(recognizer.view!.transform,
                                recognizer.scale, recognizer.scale)
  recognizer.scale = 1
}

@IBAction func handleRotate(recognizer : UIRotationGestureRecognizer) {
  recognizer.view!.transform = CGAffineTransformRotate(recognizer.view!.transform, recognizer.rotation)
  recognizer.rotation = 0
}

Just like you could get the translation from the UIPanGestureRecognizer, you can get the scale and rotation from the UIPinchGestureRecognizer and UIRotationGestureRecognizer.

Every view has a transform that is applied to it, which you can think of as information on the rotation, scale, and translation that should be applied to the view. Apple has a lot of built in functions to make working with a transform easy, such as CGAffineTransformScale (to scale a given transform) and CGAffineTransformRotate (to rotate a given transform). Here you will use these to update the view’s transform based on the gesture.

Again, since you’re updating the view each time the gesture updates, it’s very important to reset the scale and rotation back to the default state so you don’t have craziness going on.

Now hook these up in the Storyboard editor. Open up Main.storyboard and perform the following steps:

  1. Drag a Pinch Gesture Recognizer and a Rotation Gesture Recognizer on top of the monkey. Then repeat this for the banana.
  2. In the same way that you did previously, connect the Pinch Gesture Recognizers to the View Controller’s handlePinch: function.
  3. Connect the Rotation Gesture recognizers to the View Controller’s handleRotate: function.

Build and run. Run it on a device if possible, because pinches and rotations are kinda hard to do on the simulator. If you are running on the simulator, hold down the alt key and drag to simulate two fingers, and hold down shift and alt at the same time to move the simulated fingers together to a different position. Now you should be able to scale and rotate the monkey and banana!

Pinch to zoom, and drag the objects around in the running app!

Simultaneous Gesture Recognizers

You may notice that if you put one finger on the monkey, and one on the banana, you can drag them around at the same time. Kinda cool, eh?

However, you’ll notice that if you try to drag the monkey around, and in the middle of dragging bring down a second finger to attempt to pinch to zoom, it doesn’t work. By default, once one gesture recognizer on a view “claims” the gesture, no others can recognize a gesture from that point on.

However, you can change this by overriding a function in the UIGestureRecognizer delegate.

Open up ViewController.swift and mark the class as implementing UIGestureRecognizerDelegate as shown below:

class ViewController: UIViewController, UIGestureRecognizerDelegate {

Then implement one of the delegate’s optional functions:

func gestureRecognizer(UIGestureRecognizer,
 shouldRecognizeSimultaneouslyWithGestureRecognizer:UIGestureRecognizer) -> Bool {
  return true
}

This function tells the gesture recognizer whether it is OK to recognize a gesture if another (given) recognizer has already detected a gesture. The default implementation always returns false – here you switch it to always return true.

Next, open Main.storyboard, and for each gesture recognizer connect its delegate outlet to the view controller.

Build and run the app again, and now you should be able to drag the monkey, pinch to scale it, and continue dragging afterwards! You can even scale and rotate at the same time in a natural way. This makes for a much nicer experience for the user.

Programmatic UIGestureRecognizers

So far you’ve created gesture recognizers with the Storyboard editor, but what if you wanted to do things programatically?

It’s just as easy, so you’ll try it out by adding a tap gesture recognizer to play a sound effect when either of these image views are tapped.

To be able to play a sound, you’ll need to access the AVFoundation framework. At the top of Viewcontroller.swift, add:

import AVFoundation

Add the following changes to ViewController.swift just before viewDidLoad:

var chompPlayer:AVAudioPlayer? = nil

func loadSound(filename:NSString) -> AVAudioPlayer {
  let url = NSBundle.mainBundle().URLForResource(filename, withExtension: "caf")
  var error:NSError? = nil
  let player = AVAudioPlayer(contentsOfURL: url, error: &error)
  if error != nil {
    println("Error loading \(url): \(error?.localizedDescription)")
  } else {
    player.prepareToPlay()
  }
  return player
}

Replace viewDidLoad with the following:

override func viewDidLoad() {
  super.viewDidLoad()
  //1
  let filteredSubviews = self.view.subviews.filter({
    $0.isKindOfClass(UIImageView) })
  // 2
  for view in filteredSubviews  {
    // 3
    let recognizer = UITapGestureRecognizer(target: self, action:Selector("handleTap:"))
    // 4
    recognizer.delegate = self
    view.addGestureRecognizer(recognizer)

    //TODO: Add a custom gesture recognizer too
  }
  self.chompPlayer = self.loadSound("chomp")
}

Add to the bottom of the ViewController class:

func handleTap(recognizer: UITapGestureRecognizer) {
  self.chompPlayer?.play()
}

The audio playing code is outside of the scope of this tutorial so I won’t discuss it (although it is incredibly simple).

The important part is in viewDidLoad:

  1. Create a filtered array of just the monkey and banana image views
  2. Cycle through the filtered array.
  3. Create a UITapGestureRecognizer for each image view, specifying the callback.
  4. Set the delegate of the recognizer programatically, and add the recognizer to the image view.

That’s it! Compile and run, and now you should be able to tap the image views for a sound effect!

UIGestureRecognizer Dependencies

It works pretty well, except there’s one minor annoyance. If you drag an object a very slight amount, it will pan it and play the sound effect. But what you really want is to only play the sound effect if no pan occurs.

To solve this you could remove or modify the delegate callback to behave differently in the case a touch and pinch coincide, but here is another useful thing you can do with gesture recognizers: setting dependencies.

There’s a function called requireGestureRecognizerToFail: that you can call on a gesture recognizer. Can you guess what it does? ;]

Open Main.storyboard, open up the Assistant Editor, and make sure that ViewController.swift is showing there. Then control-drag from the monkey pan gesture recognizer to below the class declaration, and connect it to an outlet named monkeyPan. Repeat this for the banana pan gesture recognizer, but name the outlet bananaPan.

Then simply add these two lines to viewDidLoad, right before the TODO:

recognizer.requireGestureRecognizerToFail(monkeyPan)
recognizer.requireGestureRecognizerToFail(bananaPan)

Now the tap gesture recognizer will only get called if no pan is detected. Pretty cool eh? You might find this technique useful in some of your projects.

Custom UIGestureRecognizer

At this point you know pretty much everything you need to know to use the built-in gesture recognizers in your apps. But what if you want to detect some kind of gesture not supported by the built-in recognizers?

Well, you could always write your own! Now you’ll try it out by writing a very simple gesture recognizer to detect if you try to “tickle” the monkey or banana by moving your finger several times from left to right.

Create a new file with the iOS\Source\Swift File template. Name the file TickleGestureRecognizer.

Then replace the contents of TickleGestureRecognizer.swift with the following:

import UIKit

class TickleGestureRecognizer:UIGestureRecognizer {

  // 1
  let requiredTickles = 2
  let distanceForTickleGesture:CGFloat = 25.0

  // 2
  enum Direction:Int {
    case DirectionUnknown = 0
    case DirectionLeft
    case DirectionRight
  }

  // 3
  var tickleCount:Int = 0
  var curTickleStart:CGPoint = CGPointZero
  var lastDirection:Direction = .DirectionUnknown
}

This is what you just declared step by step:

  1. These are the constants that define what the gesture will need. Note that requiredTickles will be inferred as an Int, but you need to specify distanceForTickleGesture as a CGFloat. If you do not, then it will be inferred as a Double, and cause difficulties when doing calculations with CGPoints later on.
  2. These are the possible tickle directions.
  3. Here are the three variables to keep track of to detect this gesture:
    • tickleCount: How many times the user has switched the direction of their finger (while moving a minimum amount of points). Once the user moves their finger direction three times, you count it as a tickle gesture.
    • curTickleStart: The point where the user started moving in this tickle. You’ll update this each time the user switches direction (while moving a minimum amount of points).
    • lastDirection: The last direction the finger was moving. It will start out as unknown, and after the user moves a minimum amount you’ll check whether they’ve gone left or right and update this appropriately.

Of course, these properties here are specific to the gesture you’re detecting here – you’ll have your own if you’re making a recognizer for a different type of gesture, but you can get the general idea here.

One of the things that you’ll be changing is the state of the gesture – when a tickle is completed, you’ll need to change the state of the gesture to ended. In the original Objective-C UIGestureRecognizer, state is a read-only property, so you will need to create a Bridging Header to be able to redeclare this property.

The easiest way to do this is to create an Objective-C Class, and then delete the implementation part.

Create a new file, using the iOS\Source\Objective-C File template. Call the file Bridging-Header, and click Create. You will then be asked whether you would like to configure an Objective-C bridging header. Choose Yes. Two new files will be added to your project:

  • MonkeyPinch-Bridging-Header.h
  • Bridging-Header.m

Delete Bridging-Header.m.

Add this Objective-C code to MonkeyPinch-Bridging-Header.h:

#import <UIKit/UIGestureRecognizerSubclass.h>

Now you will be able to change the UIGestureRecognizer’s state property in TickleGestureRecognizer.swift.

Switch to TickleGestureRecognizer.swift and add the following functions to the class:

override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!)  {
  let touch = touches.anyObject() as UITouch
  self.curTickleStart = touch.locationInView(self.view)
}

override func touchesMoved(touches: NSSet!, withEvent event: UIEvent!) {
  let touch = touches.anyObject() as UITouch
  let ticklePoint = touch.locationInView(self.view)

  let moveAmt = ticklePoint.x - curTickleStart.x
  var curDirection:Direction
  if moveAmt < 0 {
    curDirection = .DirectionLeft
  } else {
    curDirection = .DirectionRight
  }

  //moveAmt is a Float, so self.distanceForTickleGesture needs to be a Float also
  if abs(moveAmt) < self.distanceForTickleGesture {
    return
  }

  if self.lastDirection == .DirectionUnknown ||
     (self.lastDirection == .DirectionLeft && curDirection == .DirectionRight) ||
     (self.lastDirection == .DirectionRight && curDirection == .DirectionLeft) {
    self.tickleCount++
    self.curTickleStart = ticklePoint
    self.lastDirection = curDirection

    if self.state == .Possible && self.tickleCount > self.requiredTickles {
      self.state = .Ended
    }
  }
}

override func reset() {
  self.tickleCount = 0
  self.curTickleStart = CGPointZero
  self.lastDirection = .DirectionUnknown
  if self.state == .Possible {
    self.state = .Failed
  }
}

override func touchesEnded(touches: NSSet!, withEvent event: UIEvent!) {
  self.reset()
}

override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) {
  self.reset()
}

There’s a lot of code here, but I’m not going to go over the specifics because frankly they’re not quite important. The important part is the general idea of how it works: you’re overriding the UIGestureRecognizer’s touchesBegan, touchesMoved, touchesEnded, and touchesCancelled functions, and writing custom code to look at the touches and detect the gesture.

Once you’ve found the gesture, you want to send updates to the callback function. You do this by changing the state property of the gesture recognizer. Usually once the gesture begins, you want to set the state to .Began, send any updates with .Changed, and finalize it with .Ended.

But for this simple gesture recognizer, once the user has tickled the object, that’s it – you just mark it as ended. The callback you will add to ViewController.swift will get called and you can implement the code there.

OK, now to use this new recognizer! Open ViewController.swift and make the following changes.

Add to the top of the class:

var hehePlayer:AVAudioPlayer? = nil

In viewDidLoad, right after TODO, add:

let recognizer2 = TickleGestureRecognizer(target: self, action: Selector("handleTickle:"))
recognizer2.delegate = self
view.addGestureRecognizer(recognizer2)

At end of viewDidLoad add:

self.hehePlayer = self.loadSound("hehehe1")

Add at the beginning of handlePan: (gotta turn off pan to recognize tickles):

//comment for panning
//uncomment for tickling
return;

At the end of the class add the callback:

func handleTickle(recognizer:TickleGestureRecognizer) {
  self.hehePlayer?.play()
}

So you can see that using this custom gesture recognizer is as simple as using the built-in ones!

Compile and run and “he he, that tickles!”

Where To Go From Here?

Here’s the download for the final project with all of the code from the above tutorial.

Congrats, you’re now a master of gesture recognizers, both built-in and your own custom ones! Touch interaction is such an important part of iOS devices and UIGestureRecognizer is the key to easy-to-use gestures beyond simple button taps.

If you have any comments or questions about this tutorial or gesture recognizers in general, please join the forum discussion below!

Credits: Artwork by Vicki Wenderlich of Game Art Guppy – Game Art Resources for Indie Game Developers.

时间: 2024-10-11 07:20:28

IOS开发—Using UIGestureRecognizer with Swift Tutoria的相关文章

iOS开发入门——17条 Swift 最佳实践规范(下)

文章来源:http://www.zretc.com/technologyDetail/433.html 承接上文:iOS开发入门--17条 Swift 最佳实践规范(上) 9.单例(Singletons) 在Swift中单例是很简单的: class ControversyManager { static let sharedInstance = ControversyManager()} Swift 的 runtime 会保证单例的创建并且采用线程安全的方式访问. 单例通常只需要访问"share

ios开发——实用技术OC-Swift篇&amp;触摸与手势识别

iOS开发学习之触摸事件和手势识别 iOS的输入事件 触摸事件 手势识别 手机摇晃 一.iOS的输入事件 触摸事件(滑动.点击) 运动事件(摇一摇.手机倾斜.行走),不需要人为参与的 远程控制事件(耳机控制手机声音) 1??iOS事件对象都是UIEvent类的实例 UIEvent类对事件类型定义了enum常量: typedef NS_ENUM(NSInteger, UIEventType){ UIEventTypeTouches, UIEventTypeMotion, UIEventRemote

iOS开发——MVC详解&amp;Swift+OC

MVC 设计模式 这两天认真研究了一下MVC设计模式,在iOS开发中这个算是重点中的重点了,如果对MVC模式不理解或者说不会用,那么你iOS肯定学不好,或者写不出好的东西,当然本人目前也在学习中,不过既然能看到这篇文档,说明你已经开始着手学习并且想深入研究它了,个人也是研究很久才搞懂,就写下来希望对各位有用,也能方便自己以后开发中查看,好了废话不多说,下面就来详细介绍一下MVC,并且用实例验证一下在项目开发中怎么去使用它. 相信你对 MVC 设计模式 并不陌生,只是不能完全理解其中的含义或者不能

iOS开发入门——17条 Swift 最佳实践规范(上)

文章来源:http://www.zretc.com/technologyDetail/432.html 前言 这篇IOS开发入门文章是我根据在 SwiftGraphics 工作时的一系列笔记整理出来的.文中大多数建议是经过深思熟虑的,但仍可以有其他类似的解决方法.因此,如果其他方案是有意义的,这些方案会被添加上去. 这个最佳实践不是强加或者推荐 Swift 在程序.面向对象或者函数风格上的应用.更重要的是,这里要讲述的是务实的方法.如有需要的话,某些建议可能会集中在面向对象或者实用的解决方法.

IOS开发从OC到swift入门与修炼

http://www.osforce.cn/course/147?mc147=1412179E99FQ 应用前景 作为一项苹果独立发布的支持型开发语言,已经有了数个应用演示及合作开发公司的测试,相信将在未来得到更广泛的应用.某种意义上Swift作为苹果的新商业战略,将吸引更多的开发者入门,从而增强App Store和Mac Store本来就已经实力雄厚的应用数量基础[4] . 应用范围 Swift 是一种新的编程语言,用于编写 iOS 和 OS X 应用.Swift 结合了 C 和 Object

ios开发——实用技术OC-Swift篇&amp;本地通知与远程通知详解

本地通知与远程通知详解 一:本地通知 Local Notification的作用 Local Notification(本地通知) :是根据本机状态做出的通知行为,因此,凡是仅需依赖本机状态即可判断需要发出通知的行为都可以或者说应该使用Local Notification来处理.比方说:iBeacon中进入了某个Beacon region,或者说自定义的一些定时提醒等. 构建Local Notification 在iOS中,构建LocalNotification非常简单,只需要掌握好NSLoca

【iOS开发】如何用 Swift 语言进行LBS应用的开发?

本文分为三部分,第一部分详解用Swift语言开发LBS应用,并给出完整的示例与源代码:第二部分介绍如何申请LBS密钥,第三部分是综合示例查看,扫描二维码即可查看示例demo. 第一部分 使用Swift语言开发LBS应用 1.下载iOS地图SDK的最新版本,地址:http://lbs.amap.com/api/ios-sdk/down/ 2.申请LBS密钥(见第二部分). 3.xCode新建工程 新建一个 Single View Application 工程.注意:Language 选择 Swif

iOS开发——完整项目实战Swift篇&amp;百思不得姐Swift版总结(二)

百思不得姐Swift版总结(二) tabBar和NavBar配色方案 一.常规主题色使用点 应用在发布前都会对其主题色进行设置,以统一应用的风格(可能有多套主题).在主题色设置上有几个方面,如下: 1.TabBar部分,设置图片高亮.文本高度颜色 2.NavigationBar部分,设置导航栏颜色及字体颜色 3.应用标签等,设置字体的颜色 4.应用图片主题色 主题色的设置点,大体从上面四个方面着手,图片的主题色我们可通过图片更换的方式进行处理.而通过代码来处理的1-3条,有着不同的处理方法.大家

iOS开发之-- oc 和 swift混编之自建桥接文件

进行swift开发的时候,oc 的项目已经进行了很长一段时间,所以默认使用Xcode自建的桥接文件的时候,这个桥接文件名称是固定的,放置的目录也是无法更改的,所以我就想自己创建一个桥接文件,然后在target里配置一下,但是编译后发现系统一直提示,桥接文件找不到,所以我又找了找方法,研究了一下如何自己建立桥接文件. 1.建立一个 Header 头文件,将它放置在自己想要放置的文件下: 这里我还是取名叫做 "iHome-Bridging-Header",放在了根目录下的 SupportF