文件、自定制视图、代码版 helloworld
这次的作业都比较简单,也开始涉及到了iOS的UI,所以现在创建的工程至少要使用单视图工程才可以完成。具体步骤不再赘述,直接上代码。
第一题:
let manager = FileManager.default
let document = manager.urls(for: .documentDirectory, in: .userDomainMask).first?.path
let file = document?.appending("/image") //图片文件夹
//print(document!) //输出Document路径,方便查看
if manager.fileExists(atPath: file!) { //若该文件夹存在
let image = file?.appending("/bd.png") //图片文件
if manager.fileExists(atPath: image!) { //若该文件存在,则显示到界面上
do{
let data = try Data(contentsOf: URL(fileURLWithPath: image!))
let img = UIImage(data: data)
let imageView = UIImageView(image: img)
imageView.frame = CGRect(x: 0, y: 100, width: 400, height: 300)
self.view.addSubview(imageView)
} catch {
print(error)
}
} else { //若不存在,则从网络下载一个图片并保存为图片文件
let url = URL(string: "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png")
do{
let data = try Data(contentsOf: url!)
try data.write(to: URL(fileURLWithPath: image!), options: .atomicWrite)
print("文件不存在,已成功创建文件")
} catch {
print(error)
}
}
} else { //若该文件夹不存在,则创建该文件夹
do {
try manager.createDirectory(atPath: file!, withIntermediateDirectories: true, attributes: nil)
print("文件夹不存在,已成功创建文件夹")
} catch {
print(error)
}
}
因为只是学习使用,所以为了方便,这部分代码可以直接写到viewDidLoad方法中。接下来再贴一张在模拟器中运行的效果图
第二题:
首先创建自定义的UIView
class MyView: UIView {
override func draw(_ rect: CGRect) {
let path = UIBezierPath(ovalIn: rect)
UIColor.red.setStroke() //红色边界
path.stroke()
UIColor.yellow.setFill() //黄色填充
path.fill()
}
}
然后在ViewController中使用自定义的UIView创建一个椭圆和一个正圆
let oval = MyView(frame: CGRect(x: 100, y: 100, width: 150, height: 100))
oval.backgroundColor = UIColor.clear
self.view.addSubview(oval)
let circle = MyView(frame: CGRect(x: 100, y: 300, width: 100, height: 100))
circle.backgroundColor = UIColor.clear
self.view.addSubview(circle)
最后时模拟器运行的效果
第三题:
class ViewController: UIViewController {
var label: UILabel!
var btn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
label = UILabel(frame: CGRect(x: 100, y: 100, width: 200, height: 44))
label.text = "hello Swift"
label.font = UIFont.systemFont(ofSize: 22)
label.textColor = UIColor.black
self.view.addSubview(label)
btn = UIButton(frame: CGRect(x: 100, y: 400, width: 50, height: 37))
btn.setTitle("Click", for: .normal)
btn.backgroundColor = UIColor.brown
btn.setTitleColor(UIColor.black, for: .highlighted)
self.view.addSubview(btn)
btn.addTarget(self, action: #selector(cilcked), for: .touchUpInside)
}
@IBAction func cilcked() {
if label.text! == "Clicked" {
label.text = "hello Swift"
btn.setTitle("Click", for: .normal)
} else {
label.text = "Clicked"
btn.setTitle("hello", for: .normal)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
因为这里涉及的代码不只在viewDidLoad方法中,所以贴了整个ViewController的代码。接下来看运行效果: