初学swift,写此文谨用来记录。
都说用过OC的再来学swift上手快,这点我不反对,但刚接触swift时真的很不适应。
首先就是swift没有宏!!!wtf!!!无奈之下,只能去造一些假宏,比如设备宽高。刚开始可能以为就是这样:
let Screen_width = UIScreen.main.bounds.size.width//屏幕宽度
let Screen_height = UIScreen.main.bounds.size.height//屏幕高度
但这样,由于不像宏一样在之后不会调用UIScreen.main.bounds.size.width这段代码,也就是Screen_width就不会随着翻转屏幕而改变,这样显然是不行的。所以,swift大多数宏都建议用函数去写
比如:
func Screen_width()->CGFloat{
return UIScreen.main.bounds.size.width//屏幕宽度
}
func Screen_height()->CGFloat{
return UIScreen.main.bounds.size.height//屏幕宽度
}
再比如获取随机色,rgb色等等:
func RGBA(r:CGFloat,g:CGFloat,b:CGFloat,a:CGFloat) ->UIColor{
return UIColor(red: r, green: g, blue: b, alpha: a)
}
func randomColor() ->UIColor{
return RGBA(r:CGFloat(arc4random()%5)/256.0, g:CGFloat(arc4random()%5)/256.0, b:CGFloat(arc4random()%5)/256.0, a:1.0)
}
func UIColorFromRGB (rgbValue:NSInteger)->UIColor{
letr = ((rgbValue &0xFF0000) >>16)
letg = CGFloat((rgbValue &0xFF00) >>8)
letb = CGFloat(rgbValue &0xFF)
return RGBA(r: r/255.0, g: g/255.0, b: b/255.0, a:1.0)
}
再比如自定义打印,延迟执行函数:
func WY_NSLOG1(_messsage :T, file :String=#file, funcName :String=#function) {
#ifDEBUG
let fileName = (file as NSString).lastPathComponent
print("\(fileName):(\(funcName)):\(messsage)")
#endif
}
typealias funcBlock = () -> ()
func Delay(time:Double,action:funcBlock!){
let delay =DispatchTime.now() + time
DispatchQueue.main.asyncAfter(deadline: delay) {
action()
}
}
虽然看起来比宏要难用,但好歹是能满足我们需求的。swift作为苹果取代oc的语言,优点自然是多多,这里就不再多说。说下swift单例吧
OC单例:
+ (id) shareInstance
{
static dispatch_once_t onceToken;
static TestMananger * manager =nil;
dispatch_once(&onceToken, ^{
manager = [[TestMananger alloc] init];
});
return manager;
}
swift单例:
classBasicApi:NSObject{
static let sharedInstance =BasicApi()
}
一句话单例,确实好用。。。
首先声明:
let imageHeight:CGFloat=169.0//图片真实尺寸高度
let imageView = UIImageView()
创建scrollview
let scrollView:UIScrollView = UIScrollView(frame:self.view.bounds)
scrollView.contentSize = CGSize(width:0,height:Screen_height()*2)
scrollView.delegate = self
scrollView.backgroundColor = randomColor()
scrollView.showsVerticalScrollIndicator = false
imageView.frame = CGRect(x:0,y:0,width:Screen_width(),height:imageHeight)
imageView.image = UIImage.init(named:"image.jpg")
imageView.contentMode = UIViewContentMode.scaleAspectFill;
scrollView.addSubview(imageView)
self.view.addSubview(scrollView)
实现代理
/*
*UIScrollViewDelegate
*/
func scrollViewDidScroll(_scrollView:UIScrollView) {
lety = scrollView.contentOffset.y
if y < 0 {
/*
*这里也是优于OC的一点,用过OC的都懂=_=
*/
imageView.frame.origin.y = y
imageView.frame.size.height = -y +imageHeight
}
WY_NSLOG1(y)
}
就这样,在下拉时,图片的位置不变,尺寸变大,这种动画算是比较常见的了
