UIImageView
//创建一个图片视图
let imageView = UIImageView(image: UIImage(named: "qiongenxuenuo"))
//设置图片的大小位置
imageView.frame = CGRect(x: 0, y: 0, width: SCWith, height: (imageView.image?.size.height)!)
//将图片添加到里面控制器视图
view.addSubview(imageView)
//保持图片比例
imageView.contentMode = .scaleAspectFit
从网络加载图片
let url = URL(string:"http://dl.bizhi.sogou.com/images/2012/01/19/191337.png")!
//从网络获取数据流
var dataV = Data()
do {
let data = try Data(contentsOf: url)
dataV = data
} catch {
print("出现异常")
}
//通过数据流初始化图片
let dataImageView = UIImageView(image: newImage)
dataImageView.frame = CGRect(x: 0, y: imageView.frame.size.height, width: 120, height: 80)
view.addSubview(dataImageView)
从网络加载图片时,需要在项目的info.plist文件中添加一个App Transport Security Settings属性,并将该字典下的Allow Arbitrary Loads的值设为设为YES
在使用到Data的方法的时候,编译出现错误“Call can throw, but it is not marked with try; and the error is not handled”,该错误的意思是需要抛出异常,抛出异常主要有三种方法
方式一:try方式,手动捕捉异常
do {
let data = try Data(contentsOf: url)
dataV = data
} catch {
// error异常的对象
print(error)
}
方式二:try?方式(常用方式) 系统帮助我们处理异常,如果该方法出现了异常,则该方法返回nil.如果没有异常,则返回对应的对象
guard let dataV = try? Data(contentsOf: url) else {
return
}
方式三:try!方法(不建议,非常危险) 直接告诉系统,该方法没有异常.注意:如果该方法出现了异常,那么程序会报错(崩溃)
let dataV = try! Data(contentsOf: url)
UISegmentedControl分段选择器
//按钮的选择项
let items = ["第一" as AnyObject, "第二" as AnyObject, "第三" as AnyObject] as [AnyObject]
let segmentedController = UISegmentedControl(items: items)
segmentedController.frame = CGRect(x: 0, y: SCHight / 2, width: SCWith, height: 44)
//默认选中页
segmentedController.selectedSegmentIndex = 0
//添加只是改变监听
segmentedController.addTarget(self, action: #selector(segmentChange(segmented:)), for: .valueChanged)
view.addSubview(segmentedController)
//添加选项
segmentedController.insertSegment(withTitle: "第四", at: items.count, animated: true)
//移除选项
//segmentedController.removeSegment(at: items.count, animated: true)
//修改选项的颜色
segmentedController.tintColor = UIColor.orange
//修改选项的文字
segmentedController.setTitle("第五", forSegmentAt: 0)
//修改选项内容便宜位置
//segmentedController.setContentOffset(CGSize(width: 20, height: 10) , forSegmentAt: 1)
//设置背景颜色
segmentedController.backgroundColor = UIColor.black
监听方法
func segmentChange(segmented: UISegmentedControl) {
//获得选项的索引
print(segmented.selectedSegmentIndex)
//获得选项文字如果为图片,则输出为空
switch segmented.selectedSegmentIndex {
case 0:
print(segmented.titleForSegment(at: segmented.selectedSegmentIndex))
case 1:
print(segmented.titleForSegment(at: segmented.selectedSegmentIndex))
case 2:
print(segmented.titleForSegment(at: segmented.selectedSegmentIndex))
case 3:
print(segmented.titleForSegment(at: segmented.selectedSegmentIndex))
default:
print(segmented.titleForSegment(at: segmented.selectedSegmentIndex))
}
}