Swift小技巧(七)

1.如何使用定位,获取当前位置信息

//1.在info.plist中,添加字段:Privacy - Location When In Use Usage Description和对应的描述(PS:可以按需求选择别的字段,比如一直后台访问,一直使用定位等)
屏幕快照 2017-05-12 上午10.34.30.png
//2.导入头文件
import CoreLocation
//3.加上如下代码
let locationManager = CLLocationManager()

locationManager.requestWhenInUseAuthorization()
        
        if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
            locationManager.startUpdatingLocation()
        }
//4.回调中得到位置信息
extension ViewController: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let locValue = manager.location!.coordinate
        print("locations = \(locValue.latitude) \(locValue.longitude)")
    }
}

2.继承自NSObject的swift类和不继承NSObject的类的区别

1.继承后,该swift类就是OC的基类的子类
2.继承后,可以使用objc_msgSend()等运行时的方法
3.继承后,可以提供OC运行时的数据
也就是说继承后的swift类,就会具有OC的运行时的特性,以及一些NSObject类具有的特性。如果不会用到这些特性,那么跟OC不同,可以不继承NSObject类。

3.如何使用数组的切片功能

        let arr = [1, 2, 3, 4]
        print(arr[0...2])//[1, 2, 3]
        print(arr[0..<2])//[1, 2]

4.不是继承自NSObject的类,如何使用具有运行时特性的Timer

class Person {
            func startTimer() {
                Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(start(timer:)), userInfo: nil, repeats: true)
            }
            //如下,在该方法前面加上@objc。因为Timer是使用的消息转发机制来调用目标选择器的,
            //而消息转发机制是继承了NSObject类才会有的特性。
            //所以,另外一种方法是,让Person继承自NSObject类。
            @objc func start(timer: Timer) {
                print("开始")
            }
        }
        
        let person = Person()
        person.startTimer()

5.如何实现某个VC出现时,导航栏消失,VC释放后,导航栏显示

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.navigationController?.setNavigationBarHidden(true, animated: animated)
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    self.navigationController?.setNavigationBarHidden(false, animated: animated)
}

6.如何快速获得最大最小值

        let a = 1
        let b = 3
        print(max(a, b))
        print(min(a, b))

7.如何给tableview设置左划,出现删除按钮

//返回指定的cell是否可以编辑
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}
//如果点击了左划出现的按钮,这里会被调用
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if (editingStyle == UITableViewCellEditingStyle.delete) {
        //如果点击的是删除样式的按钮
    }
}
//重写该方法,可以编辑按钮的文字
func tableView(tableView:UITableView,titleForDeleteConfirmationButtonForRowAtIndexPath indexPath:NSIndexPath) - > String?{
//返回文本
} 

8.如何设置方法,如果子类没有重写该方法,就抛出异常或者报错,适用于写接口。

class A {
    func fun() {
        preconditionFailure("必须要被重写!")
    }
}

class B: A {
    override func fun() {
        print("正常")
    }
}

let b = B()
//如果没有重写,调用fun会报错
b.fun()

9.swift中如何打印变量的地址

//在OC中,这样使用
[NSString stringWithFormat:@"%p", myVar]

//在swift中,这样子
var str = "a"
withUnsafePointer(to: &str) {
    print("str的地址是:\($0)")
}

10.如何获得设备方向的变化

//添加设备方向变化的监听
NotificationCenter.default.addObserver(self, selector: #selector(rotated), name: Notification.Name.UIDeviceOrientationDidChange, object: nil)
 //不使用了需要移除
NotificationCenter.default.removeObserver(self, name: Notification.Name.UIDeviceOrientationDidChange, object: nil)
//方法
    func rotated() {
        if UIDeviceOrientationIsLandscape(UIDevice.current.orientation) {
            print("水平")
        }
        if UIDeviceOrientationIsPortrait(UIDevice.current.orientation) {
            print("竖直")
        }
    }


//或者,在vc中,重写下面的方法
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        if UIDevice.current.orientation.isLandscape {
            print("水平的")
        }
        if UIDevice.current.orientation.isPortrait {
            print("竖直的")
        }
    }

11.如何获得APP的唯一的标示符

let uuid = UIDevice.current.identifierForVendor!.uuidString
//该ID,只要APP不卸载的情况下,不会改变。

12.如何指定某个方法参数需要遵循多个协议

protocol SomeProtocol {}
protocol OhterProtocol {}
//使用协议&组合协议
func fun<T: SomeProtocol & OhterProtocol>(arg: T) {
    
}
//或者使用where
func fun2<T>(arg: T) where T:SomeProtocol, T:OhterProtocol {
    
}

13.swift的扩展可以做的事情有哪些?

1.添加计算属性和计算静态属性
2.定义实例方法和类型方法
3.提供新的初始化器
4.定义下标
5.定义和使用新的嵌套类型
6.使现有类型符合协议

14.如何快速的去掉域名的后缀

extension String {
    var nsValue: NSString {
        return self as NSString
    }
}
//转换成nsstring后,使用已经存在的方法,会很快的实现。
//某些string没有的方法,可以将其转换成nsstring,使用现成的方法。
let myString = "www.baidu.com".nsValue.deletingPathExtension
//"www.baidu"

15.如何定义一个属性,让其在内部是可写的,在外部是可读写的

//如下,在关键字后方加上(),在内部写上set或get即可。
private(set) public var property: Int

16.如何初始化range

let range: Range<Int> = 1 ..< 4
//或者
let range2 = 1 ..< 4

17.如何快速的给uitextfield添加下划线

//扩展一个方法
extension UITextField {
    func setBottomBorder() {
        borderStyle = .none
        layer.backgroundColor = UIColor.white.cgColor
        
        layer.masksToBounds = false
        layer.shadowColor = UIColor.gray.cgColor
        layer.shadowOffset = CGSize(width: 0, height: 1)
        layer.shadowOpacity = 1
        layer.shadowRadius = 0
    }
}

//使用
let field = UITextField(frame: CGRect(x: 100, y: 100, width: view.frame.width-200, height: 30))
        field.placeholder = "请输入:"
        field.setBottomBorder()
        view.addSubview(field)

结果如图:

屏幕快照 2017-05-16 上午11.25.19.png

18.如何随机生成字母与数字组合的指定长度的字符串

extension String {
    static func random(length: Int = 20) -> String {
        let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        var randomString: String = ""
        for _ in 0..<length {
            let randomValue = arc4random_uniform(UInt32(base.characters.count))
            randomString += "\(base[base.index(base.startIndex, offsetBy: Int(randomValue))])"
        }
        return randomString
    }
}

let s = String.random()

19.如何像OC使用block作为变量一样使用swift中的闭包也作为变量

//OC中,我们这样使用block
@interface PopupView : UIView
@property (nonatomic, copy) void (^onHideComplete)();
@end

@interface PopupView ()
- (IBAction)hideButtonDidTouch:(id sender) {
    if (onHideComplete) onHideComplete ();
}
@end

PopupView * popupView = [[PopupView alloc] init]
popupView.onHideComplete = ^() {
}



//下面是使用swift的时候
class PopupView: UIView {
    var completionHandler: (() -> Void)?
    func fun() {
        if let handler = completionHandler {
            handler()
        }
    }
}

let pop = PopupView()
pop.completionHandler = {
    print("处理回调!")
}
pop.fun()

20.如何播放bundle的音源

import AudioToolbox

class Sound {
    var soundEffect: SystemSoundID = 0
    init(name: String, type: String) {
        let path  = NSBundle.mainBundle().pathForResource(name, ofType: type)!
        let pathURL = NSURL(fileURLWithPath: path)
        AudioServicesCreateSystemSoundID(pathURL as CFURLRef, &soundEffect)
    }

    func play() {
        AudioServicesPlaySystemSound(soundEffect)
    }
}

//用法:
testSound = Sound(name: "test", type: "caf")
testSound.play()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,556评论 4 61
  • 医药代表从业新规征求意见:医药代表不得承担药品销售任务,个人信息需登记备案。 草译两首诗做个对比,纯属个人看法。 ...
    炼心清秋阅读 1,234评论 0 0
  • 前几天,江思远分享了他和蜜蜂的亲密接触! 他分享过后,过了一两天,真是说曹操曹操就到了。这可不是江思远说的蜜蜂,他...
    薛淏文阅读 1,950评论 1 0
  • oejd1uejdumernirjn♀jdnekrijdj┏ugghhbvvあieeeisghghegddjrif...
    邹江涛阅读 3,339评论 0 0
  • 本来想写写想象过的以后得生活~但是有点晚了写不完了~ 决定明天再写 只能说有你让我的生活更丰富更好 填补了很多空白...
    uaremybelief阅读 1,801评论 0 0

友情链接更多精彩内容