[super viewDidLoad];
self.view.backgroundColor=[UIColor redColor];<img src="F:\Learn of iOS\Image\Image00\image-20220513174436323.png" alt="image-20220513174436323" style="zoom:67%;" />
iOS学习
MAC指南
触控板操作;
ctrl+command+F:新建桌面;来回挠三指切换。
ctrl+command++:放大;
ctrl+l:清屏
pwd家目录
C语言课程
- MAC下搭建C语言开发环境
- 数据类型
- 运算符和表达式
- 条件控制语句,循环控制语句
- 函数,数组,指针,字符串
- 复杂数据类型
- 文件操作
int a,aa;
scanf("%d,%d",&a,&aa);
//无条件转向语句goto标签,不提倡使用
printf("1\n");
printf("2\n");
goto l;
printf("3\n");
l:
printf("4\n");
switch(a)
{
case:0
printf("0");break;
..
default:
break;
}
//在C语言中,字符串就是使用字符数组来保存的。
char ch[]="hello";
char ch[]={'h','e','l','l','o','\0'};
while可能一次不执行,do while至少执行一次。
#include <string.h>
strlen(const char *)
strcmp(const char *,const char *)
strcat(str1,str2) //后者加到前者
strcpy(str1,str2) //拷贝
//结构体中不让直接赋值
struct Student{
char name[20];
char sex[4];
int age;
};
struct Student zs;//使用别名去掉struct
//zs.name="mafu"; 不能直接赋值
strcpy(zs.name, "mafu");
strcpy(zs.sex, "man");
------------------------------------
typedef struct tagStudent{
char name[20];
char sex[4];
int age;
}Student;
Student *zs=malloc(sizeof(Student));
//zs.name="mafu"; 不能直接赋值
strcpy(zs->name, "mafu");
strcpy(zs->sex, "man");
zs->age=21;
printf("name:%s\n",zs->name);
-----------------------------------
//结构体嵌套
结构和联合union区别:
struct Student{//成员变量的内存是独立的
int number;
char name[20];
};
union Xinxi{//成员变量的内存是共用的,谁大用谁,问题:同一时间只能使用一个成员
int number;
char name[20];
};
这种情况下联合就好:结构体大部分相同
枚举就是罗列值,比如月。枚举和联合一样,都是固定里面的值。
enum number{one=0,two,three};//本身是对应值得,而且递增,默认0
enum number n;
n=one;
n=two;
n=three;
文件操作
//1.打开文件,2.操作文件读写,3.关闭文件
FILE *fp=NULL;
fp=fopen("/Users/mafu/xcode_project/c02/c02/abc.txt", "w");
if (fp==NULL) {
printf("文件打开失败");
exit(1);
}
//写文件:fputc fputs fprintf用格式化写
fputc('a', fp);
fputc('\n', fp);
fputs("aaaa\n", fp);
fprintf(fp, "%-3d\n",1);
fclose(fp);//这个语句应该与打开一对写
-----------------------------------------------------------------------
//读文件
FILE *fp=NULL;
fp=fopen("/Users/mafu/xcode_project/c02/c02/abc.txt", "r");
if (fp==NULL) {
printf("文件打开失败");
exit(1);
}
//一行一行读取文件
char *str=malloc(100);
while (fgets(str, 100, fp)!=NULL) {
printf("%s",str);
}
free(str);
str=NULL;
fclose(fp);//这个语句应该与打开一对写
--------------------------------------------------------
//二进制形式读写文件fwrite fread
FILE *fp=NULL;
fp=fopen("/Users/mafu/xcode_project/c02/c02/abc.dat","rb");
int num[6];
//int num[]={1,2,3,4,5,6};
//fwrite(num, sizeof(num), 1, fp);
fread(num, sizeof(num), 1, fp);
for (int i=0; i<6; i++) {
printf("%d\t",num[i]);
}
fclose(fp);
预编译又叫做预处理。#include #define。条件编译。
彩票机选系统21选5
srandom((unsigned)time(NULL));//初始化随机函数
int num[5];
for(int i=0;i<5;i++){
// printf("%ld\t",random()%21+1);//有重复?
num[i]=random()%21+1;
for(int k=0;k<i;k++){
if(num[k]==num[i]) break;
}
if(k==i) printf("%d\t",num[i]);
else i--;
}
//选择排序:每次选择最小的放在前面
for(int i=0;i<9;i++)
{
for(int j=i+1;j<10;j++){
if(num[i]<num[j]){//num[i]固定
int t=num[i];
num[i]=num[j];
num[j]=t;
}
}
}
斗地主发牌器
int cards[54];
for(int i=0;i<54;i++){//初始化
cards[i]=i;
}
//混牌
srandom((unsigned)time(NULL));//随机函数初始化
for(int i=0;i<30;i++){
int a=random()%54;
int b=random()%54;
int t=cards[a];
cards[a]=cards[b];
cards[b]=t;
}
/*
for(int i=0;i<54;i++){
int temp=cards[i]/13;
if(cards[i]==52) printf("小王\t");
else if(cards[i]==53) printf("大王\t");
else if(temp==0) printf("♠%02d\t",cards[i]%13+1);//02d表示以两位的形式进行显示如果不足两位补0
else if(temp==1) printf("♥%02d\t",cards[i]%13+1);
else if(temp==2) printf("﹢%02d\t",cards[i]%13+1);
else (temp==3) printf("♣%02d\t",cards[i]%13+1);
if((i+1)%13==0) printf("\n")
}
*/
char styles[4][10]={"♠","♥","﹢","♣"};
char number[13][3]={"A","1","2","3","4","5","6","7","8","9","10","J","Q","K"};
for(int i=0;i<54;i++){
int temp=cards[i]/13;
if(cards[i]==52) printf("小王\t");
else if(cards[i]==53) printf("大王\t");
else{
printf("%s%s",styles[temp],number[cards[i]%13+1]);
}
if((i+1)%13==0) printf("\n")
}
学生成绩管理系统
//字符串4个函数:拷贝,连接,比较,取长度
strcpy(ch,"hhh");
strcat(ch,"hhh");
strcmp(ch,"hhh");
strlen(ch);
#define STUDENTS 100
#define ITEMS 10
int n;//总人数
int k;//科目总数
char name[STUDENTS][40];
char itemname[ITEMS][40];
int score[STUDENTS][ITEMS];
printf("输入班级总人数:");
scanf("%d",&n);
printf("输入科目总数:");
scanf("%d",&k);
for(int i=0;i<k;i++){
printf("输入地%d科名称:",i+1);
scanf("%s",itemname[i]);
}
for(int i=0;i<n;i++){
printf("输入第%d名同学姓名:",i+1);
scanf("%s",name[i]);
for(int j=0;j<k;j++){
printf("输入%s科的成绩:",itemname[j]);
scanf("%s",score[i][j]);
}
}
//使用指针
int n;//总人数
int k;//科目总数
char name[STUDENTS][40];
char itemname[ITEMS][40];
int score[STUDENTS][ITEMS];
void input(int *,int *,char[][40],char[][40],int[][ITEMS]);
input(&n, &k, name, itemname,score);
return 0;
}
void input(int *n,int *k,char name[][40],
char itemname[][40],int score[][ITEMS]){
printf("输入班级总人数:");
scanf("%d",n);
printf("输入科目总数:");
scanf("%d",k);
for(int i=0;i<*k;i++){
printf("输入第%d科名称:",i+1);
scanf("%s",itemname[i]);
}
for(int i=0;i<*n;i++){
printf("输入第%d名同学姓名:",i+1);
scanf("%s",name[i]);
score[i][*k]=0;
for(int j=0;j<*k;j++){
printf("输入%s科的成绩:",itemname[j]);
scanf("%d",&score[i][j]);
score[i][*k]+=score[i][j];
}
}
}
void show(int *n,int *k,char name[][40],
char itemname[][40],int score[][ITEMS]){
printf("姓名\t");
for (int i=0; i<*k; i++) {
printf("%s\t",itemname[i]);
}
printf("总分\t");
printf("\n");
for (int i=0; i<*n; i++) {
printf("%s\t",name[i]);
for (int j=0; j<=*k; j++) {
printf("%d\t",score[i][j]);
}
printf("\n");
}
printf("\n");
}
void sort(int *n,int *k,char name[][40],
char itemname[][40],int score[][ITEMS]){
for(int i=0;i<*n-1;i++){
for(int j=i+1;j<*n;j++){
//调换总分
if(score[j][*k]>score[i][*k]){
int t=score[i][*k];
score[i][*k]=score[j][*k];
score[j][*k]=t;
char temp[40];
strcpy(temp,name[i]);
strcpy(name[i],name[j]);
strcpy(name[j],temp);
for(int m=0;m<*k;m++){
t=score[i][m];
score[i][m]=score[j][m];
score[j][m]=t;
}
}
}
}
}
//使用结构struct改写代码
我的通讯录
//添加、删除、查找,修改一个联系人,显示所有联系人
while(1){
printf("欢迎使用通讯录\n");
printf("(1)添加联系人\n");
printf("(2)删除联系人\n");
printf("(3)查找联系人\n");
printf("(4)修改联系人\n");
printf("(5)修改联系人\n");
printf("(6)exit\n");
//int order=0;
char ch;
scanf("输入选择:%d",&ch);
switch(ch){
1:
add();
break;
2:
deltete();
break;
3:
find();
break;
4:
update();
break;
5:
show();
break;
6:
exit(0);
break;
default:
printf("输入正确数字\n");
break;
}
}
//对于复杂的结构体等数据,应该保存在二进制文件中。
void init(){
FILE * fp=NULL;
fp=fopen("telbook.bat","rb");
int count=0;
if(fp==NULL){
fp=fopen("telbook.bat",sizeof(count),1,fp);
fwrite(&count,sizeof(count),1,fp);
fclose(fp);
}
else{
fread(&n,sizeof(int),1,fp);//n为人数
for(int i=0;i<n;i++){
fread(&persons[i],sizeof(Person),1,fp);
}
}
fclose(fp);
}
void add(){
scanf("%s",persons[n].name);
scanf("%s",persons[n].tel);
//数据有效性检验
n++;
write_file();
}
void write_file(){
FILE * fp=NULL;
fp=fopen("telbook.dat","wb");
for(int i=0;i<n;i++){//数据结构/数据库替代
fwrite(&persons[i],sizeof(Person),1,fp);
}
fclose(fp);
}
void delete(){
int nn;//删除编号
scanf("%d",&nn);
//提示是否确定删除信息
//删除,移动
}
void find(){
//可能有重名
}
OC课程13章
概述:main.m
#import <Foundation/Foundation.h>//#import能避免重复包含,Foundation.h包含了c的所有库
//.m文件中既可以写C代码也可以写OC代码 .mm还可以写c++代码
int main(int argc, const char * argv[]) {
@autoreleasepool {//自动释放池
/*
NSLog(@"Hello, World!");//NS相关的函数都是在Foundation库中,@代表oc独有
int i=0;
printf("c语言%d.\n",i);
*/
//新增两个数值类型
BOOL b=YES;//布尔类型,YES/NO
NSString *str=@"123";//框架中的一个类 OC中的所有对象类型都是指针类型的
NSLog(@"%d",b);
NSLog(@"%@",str);//%@表示输出的是一个对象类型
}
return 0;
}2022-05-14 21:27:33.167205+0800 OC00[1100:46940] Hello, World!//输出时间,项目,进程和线程
声明和实现:OC是面向对象的编程语言,操作对象类,C是面向结构的语言。
//类由两部分组成:类的声明,类的实现
@interface Student:NSObject //:表示继承的类
{//类由数据和操作组成
NSString *name;
int age;
}
-(void)say;
@end
@implementation Student
-(void)say
{
NSLog(@"%@今年%d岁了",name,age);
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
Student *s=[[Student alloc]init];//申请内存创建类对象
//对象里的数据无法访问
[s say];//调用对象的方法
}
return 0;
}
//创建oc类文件,声明文件.h,实现文件.m
//OC中的类没有命名空间,命名规则是自己大写+类
//.h文件
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface MFStudent : NSObject
{
NSString *name;
int age;
}
-(void)say;
-(void)setNam:(NSString *)_name;
-(void)setAge:(int)_age;
-(void)setName:(NSString *)_name andAge:(int)_age;
@end
NS_ASSUME_NONNULL_END
//.m文件
#import "MFStudent.h"
@implementation MFStudent
-(void)say{
NSLog(@"%@今年%d岁了",name,age);
}
- (void)setNam:(NSString *)_name{
name=_name;
}
- (void)setAge:(int)_age{
age=_age;
}
- (void)setName:(NSString *)_name andAge:(int)_age{
name=_name;
age=_age;
}
@end
//.m主函数调用
MFStudent * mf=[[MFStudent alloc]init];
[mf setName:@"马富"];
[mf setAge:12];
[mf say];
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface MFSum : NSObject
{
int n;
}
-(void)setN:(int)_n;
-(int)sum;
@end
NS_ASSUME_NONNULL_END
#import "MFSum.h"
@implementation MFSum
- (void)setN:(int)_n{
n=_n;
}
- (int)sum{
int s=0;
for (int i=1; i<=n; i++) {
s+=i;
}
return s;
}
@end
#import "MFSum.h"
@implementation MFSum
- (void)setN:(int)_n{
n=_n;
}
- (int)sum{
int s=0;
for (int i=1; i<=n; i++) {
s+=i;
}
return s;
}
@end
oc类的定义和使用图形类求面积
//长方形-rectangle 正方形-square 圆形-round 三角形-triangles
MFRectangle * rec=[[MFRectangle alloc]init];
[rec setWidth:100 andHeight:20];
int area=[rec area];
NSLog(@"rectangle'area=%d",area);
MFSquare * squ=[[MFSquare alloc]init];
[squ setSide:100];
area=[squ area];
NSLog(@"square'area:%d",area);
MFCircle * cir=[[MFCircle alloc]init];
[cir setRad:100];
double d_area=[cir area];
NSLog(@"circle'area:%lf",d_area);//%g
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface MFTriangle : NSObject
{
int bottom;
int height;
}
-(double)area;
//-(void)setBottom:(int)_bottom andHeight:(int)_height;
-(void)setBottom:(int)bottom andHeight:(int)height;
@end
NS_ASSUME_NONNULL_END
//-----------------------------------
#import "MFTriangle.h"
@implementation MFTriangle
- (double)area{
return bottom*height/2.0;
}
- (void)setBottom:(int)bottom andHeight:(int)height{
self->bottom=bottom;//self表示指向当前对象的指针,一般不提倡使用
self->height=height;
}
@end
//-----------------------------------
MFTriangle * tri=[[MFTriangle alloc]init];
[tri setBottom:3 andHeight:5];
d_area=[tri area];
NSLog(@"triangle'area:%lf",d_area);
行为:
-行为:对象行为
+行为:类行为 (也叫做工厂行为) 类似构造函数
+(id)rectangle;
+ (id)rectangle{
return [[[self class]alloc]init];
}
//MFRectangle * rec=[[MFRectangle alloc]init];
MFRectangle * rec=[MFRectangle rectangle];
c的面向对象:
//oc里面的get是有特殊用处的,所有获取数据不用get命名
-(int)width;
-(int)height;
- (int)width{
return width;
}
- (int)height{
return height;
}
// [rec setWidth:100 andHeight:20];
// rec.width=100; .操作符相当于默认调用操作函数中的setWidth(这个需要自己写)
// 获得值得时候就是调用,int w=rec.width; 真确命名规范为点操作符提供基础
//oc里面是行为调用,而不是像其他一样访问语言
-(void)setWidth:(int)_width;
-(int)width;
@public //对象数据的访问权限
int side;
square->side=100;//不提倡这样用
类的继承和init函数
//上述图形的方法具有许多相同的代码,应该抽取出来,使用继承
//-----------------------------------------
@interface MFShape : NSObject
{
int width;
int height;
}
-(id)initWithWidth:(int)_width andWithHeight:(int)_height;
-(int)area;
//-----------------------------------------
- (id)init //重写父类的init
{
self = [super init];
if (self) {
width=0;
height=0;
}
return self;
}
- (id)initWithWidth:(int)_width andWithHeight:(int)_height{
//初始化行为必须去调用父类的初始化行为
self=[super init];
if (self) {
width=_width;
height=_height;
}
return self;
}
- (int)area{
return width*height;
}
//--------------------------------------------------
//继承
MFShape * shape=[[MFShape alloc]initWithWidth:20 andWithHeight:10];
NSLog(@"shape'area=%d",[shape area]);
@interface MFShape_Rectangle : MFShape
@end
@implementation MFShape_Square
-(id)initWithSide:(int)_side{
self=[super initWithWidth:_side andWithHeight:_side];
return self;
}
@end
@implementation MFShape_Circle
-(id)initWithRad:(int)_rad{
self=[super initWithWidth:_rad andWithHeight:_rad];
return self;
}
-(double)area{
return 3.14*[super area];
}
@end
多态:使不同的类共享相同的方法名称的能力,允许将子类类型的指针赋值给父类类型的指针。
动态绑定和id类型:id通用的对象类型,可以用来存储属于任何类的对象。
id dataValue;//不用加*号,编译时和运行时检查,所以对象类型无法确定在编译的时候
静态形态,动态形态。
//NSObject的一些方法
id s=[[MFShape_Square alloc]initWithSide:10];
BOOL b=[s isKindOfClass:[MFShape_Square class]];//判断是否为类型或者父类类型
if (b) {
NSLog(@"this is a Square!");
}
//isMenberofClass判断否是类,不能判断父类,只能具体,不能判断层次
//动态加载
id s=[[MFShape_Square alloc]initWithSide:10];
//SEL指向函数指针,动态加载
SEL sel=@selector(area);
BOOL b=[s respondsToSelector:sel];
if (b) {
NSLog(@"area is exist!");
NSLog(@"square'area:%d",[s performSelector:sel]);
}
OC课程14章
OC的常用结构:
- CGPoint
- CGRect
- CGSize
//点,大小,矩形,范围
//CGPoint p={100,100};
CGPoint p=CGPointMake(10, 10);
NSLog(@"x=%lf,y=%lf",p.x,p.y);
CGSize s={20,30};
CGRect r=CGRectMake(10, 10, 12, 12);//长方形,左上角坐标长度和宽度
// r.origin.x
// r.origin.y
// r.size.width
// r.size.height
NSRange ran;
ran.location=10;
ran.length=10;
NString
OC中的NString的创建:
//初始化,行为,动态字符串,静态字符串
NSString * str=@"mafu";
//初始化,工厂行为
char * cstr="hello";//不能用这个形式,要用unicode
NSString * str1=[NSString stringWithCharacters:cstr length:strlen(cstr)];
NSLog(@"%@",str);
NSLog(@"%@",str1);
2022-05-17 20:32:57.428331+0800 OC01[644:10078] mafu
2022-05-17 20:32:57.429534+0800 OC01[644:10078] 敨汬o䀥猀
NSString * str=[NSString stringWithFormat:@"%d",123];//将数值转成字符串
NSLog(@"%@",str);
NSString * str2=@"asd";//里面的内容不会发生改变,但是指向可以改变
NSLog(@"%@",str2);
str2=@"飞跃";
NSLog(@"%@",str2);
NSString * str3=[NSString stringWithUTF8String:"飞跃"];
NSLog(@"%@",str3);
//下面初始化方式不用,对程序有负担,申请的空间回收后即丢弃,使用工厂类行为自动释放内存
NSString * str=[[NSSting alloc]init]
str=@"123";
NSString * str=@"abc";
NSLog(@"%@",str);
NSLog(@"%@",[str uppercaseString]);
NSLog(@"%@",[str lowercaseString]);
NSLog(@"%lu",(unsigned long)[str length]);
//问题:计算的时候中文字符和英文字符占字节是一样的
str=@"富bc";
NSLog(@"%lu",(unsigned long)[str length]);
NSLog(@"%lu",(unsigned long)[str lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);//中文占3个字符
str=@"123.4";
NSRange ran=[str rangeOfString:@"."];
NSLog(@"location=%lu,length=%lu",ran.location,ran.length);
if (ran.length==NSNotFound) {
NSLog(@"no");
}else{
NSLog(@"yes");
}
NSString * str=@"123.4";
if ([str isEqualToString:@"123"]) {//比较
NSLog(@"yes");
}else{
NSLog(@"no");
}
double a=[str doubleValue];//字符串,数字转换
NSLog(@"%f",a);
if ([str hasPrefix:@"1"]) {//打头
NSLog(@"yes");
}else{
NSLog(@"no");
}
if ([str hasSuffix:@"1"]) {//结尾
NSLog(@"yes");
}else{
NSLog(@"no");
}
//提取子串,左闭右开
NSLog(@"%@",[str substringFromIndex:1]);
NSLog(@"%@",[str substringToIndex:2]);
NSRange ran={2,2};
NSLog(@"%@",[str substringWithRange:ran]);
ran.location=0;
ran.length=1;
for (int i=(int)str.length-1;i>=0;i--) {
ran.location=i;
NSLog(@"%@",[str substringWithRange:ran]);
}
str=@" 12 3";
NSLog(@"%@",str);
//只能剔除开始空格
NSLog(@"%@",[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]);
//去除空格
NSLog(@"%@",[str stringByReplacingOccurrencesOfString:@" " withString:@""]);
NSMutableString
OC中的NSMutableString:
//行为写到磁盘文件
NSString * str=@"123bb马";//atomically是否使用临时文件
[str writeToFile:@"/Users/mafu/xcode_project/OC01/OC01/abc.txt" atomically:NO encoding:NSUTF8StringEncoding error:nil];
NSString * read;
NSError * error;
read=[NSString stringWithContentsOfFile:@"/Users/mafu/xcode_project/OC01/OC01/abc.txt" encoding:NSUTF8StringEncoding error:&error];
NSLog(@"%@",read);
NSLog(@"%@",error);
//字符串拼接,返回的都是新的字符串,不是指向原串了
NSString * str2=@"mmm";
NSLog(@"%@",[NSString stringWithFormat:@"%@%@",str,str2]);
NSLog(@"%@",[str stringByAppendingString:str2]);
//动态可改变字符串
NSMutableString * mstr=[NSMutableString stringWithCapacity:100];
[mstr appendString:@"123"];
NSLog(@"%@",mstr);
NSRange r={1,2};
[mstr replaceCharactersInRange:r withString:@""];
NSLog(@"%@",mstr);
NSArray与NSMutableArray
OC中的NSArray与NSMutableArray
//NSArray静态数组,只能保存对象,也能保存数值类型,@封装要
//NSArray * array=[[NSArray alloc]initWithObjects:@1,@2,@3, nil];
//NSArray * array=[[NSArray alloc]initWithObjects:@"1",@"2",@"3", nil];
//通过行为构建
//NSArray * array=[NSArray arrayWithObjects:@"1",@"2",@"3", nil];
//NSArray * array=@[@"1",@"2",@"3"];//静态数组,保存的也是对象
//静态数组不能修改
//动态数组NSMutableArray,增删改
NSMutableArray * array=[NSMutableArray arrayWithCapacity:20];
for (int i=0; i<10; i++) {
[array addObject:[NSString stringWithFormat:@"%d",i+1]];
}
[array removeLastObject];
[array removeObject:@"2"];
[array removeObjectAtIndex:2];
[array insertObject:@"a" atIndex:0];
NSLog(@"%lu",(unsigned long)[array count]);
for (int i=0; i<[array count]; i++) {
NSLog(@"%@",array[i]);//[array objectAtIndex:i]
}
//快速遍历 for in
for(NSString * str in array){
NSLog(@"%@",str);
}
NSSet和NSDictionary
OC中的集合NSSet和NSDictionary:
//NSSet * set=[NSSet setWithObjects:@"1",@"2",@"3",@"1",nil];
// NSArray * arr=[set allObjects];
// arr=[arr sortedArrayUsingSelector:@selector(compare:)];
// for(NSString * str in arr){
// NSLog(@"%@",str);
// }
NSMutableSet * set=[NSMutableSet setWithCapacity:20];
[set addObject:@"1"];
[set addObject:@"1"];
[set addObject:@"2"];
[set addObject:@"3"];
[set addObject:@"4"];
[set removeObject:@"1"];
for(NSString * str in set){
NSLog(@"%@",str);
}
//NSDictionary* dictionray=@{@"1":@"a1",@"2":@"a2"};
// NSDictionary* dictionray=[NSDictionary dictionaryWithObjectsAndKeys:@"张三",@"1",@"李四",@"2", nil];
// NSDictionary* dictionray=[[NSDictionary alloc]initWithObjectsAndKeys:@"张三",@"1",@"李四",@"2", nil];
//动态字典
NSMutableDictionary * dictionary=[[NSMutableDictionary alloc]initWithCapacity:20];
[dictionary setObject:@"张三" forKey:@"1"];
[dictionary setObject:@"李四" forKey:@"2"];
NSArray * key=[dictionary allKeys];
for(NSString * str in key){
NSLog(@"%@,%@",str,[dictionary objectForKey:str]);
}
NSValue和NSNumber
OC中的NSValue和NSNumber:
//尝试使用数组保存
CGPoint p1={1,1};
CGPoint p2={2,2};
CGPoint p3={3,3};
//报错,因为点不是对象而是实例化过程内容
//NSArray * array=[NSArray arrayWithObjects:p1,p2,p3 nil];
NSValue * v1=[NSValue valueWithPoint:p1];
NSValue * v2=[NSValue valueWithPoint:p2];
NSValue * v3=[NSValue valueWithPoint:p3];
NSArray * array=[NSArray arrayWithObjects:v1,v2,v3, nil];
for(NSValue * v in array){
NSPoint p=[v pointValue];
NSLog(@"%@",v);
NSLog(@"x=%f,y=%f",p.x,p.y);
}
NSMutableArray * marray=[NSMutableArray arrayWithCapacity:20];
for (int i=10; i<15; i++) {
[marray addObject:[NSNumber numberWithUnsignedInt:i]];
}
for(NSNumber * num in marray){
NSLog(@"%d",[num intValue]);
}
NSData
OC的NSData:
// NSArray * array=[[NSArray alloc]initWithObjects:@"11",@"22",@"33", nil];
//
// [array writeToFile:@"/Users/mafu/xcode_project/OC01/OC01/array.plist" atomically:YES];
// NSArray * read=[NSArray arrayWithContentsOfFile:@"/Users/mafu/xcode_project/OC01/OC01/array.plist"];
// NSLog(@"%@",read);
NSDictionary * dic=[[NSDictionary alloc]initWithObjectsAndKeys:@"a",@"1",@"b",@"2", nil];
[dic writeToFile:@"/Users/mafu/xcode_project/OC01/OC01/array.plist" atomically:YES];
NSDictionary * readd=[[NSDictionary alloc]initWithContentsOfFile:@"/Users/mafu/xcode_project/OC01/OC01/array.plist"];
NSLog(@"%@",readd);
//保存二进制数据
NSData * data=[NSData dataWithContentsOfFile:@"/Users/mafu/xcode_project/OC01/OC01/img.jpg"];
NSLog(@"%ld",data.length);
//8bit(位)=1Byte(字节)
//1024字节=1KB
//1024kB=1MB
//但是磁盘显示25.3MB 直接除1000?
NSLog(@"%lf",(double)data.length/(1024*1024));
unsigned char * ch=[data bytes];
NSLog(@"%x,%x",ch[0],ch[1]);
[data writeToFile:@"temp.jpg" atomically:YES];
OC课程15章
arc和非arc
内存管理之arc和非arc:
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface MFStudent : NSObject
{
NSString * name;
}
-(void)setName:(NSString *)_name;
@end
NS_ASSUME_NONNULL_END
//-----------------------------自动释放内存
#import "MFStudent.h"
@implementation MFStudent
-(void)dealloc{
NSLog(@"被销毁");
}
- (void)setName:(NSString *)_name{
name=_name;
}
@end
//-----------------------------
#import <Foundation/Foundation.h>
#import "MFStudent.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
MFStudent * ms=[[MFStudent alloc]init];
[ms setName:@"马富"];
}
return 0;
}
自动引用计数:
-(void)dealloc{
NSLog(@"%@被销毁",name);
[super dealloc];
}
//没被销毁输出
NSLog(@"%lu",(unsigned long)[ms retainCount]);//引用个数
[ms release];
静态分析,分析内存泄漏
strong与retain
内存管理之strong与retain:
//引用计数 alloc +1
MFStudent * ms=[[MFStudent alloc]init];
[ms setName:@"马富"];
MFStudent * ms2=[ms retain];//ms2 ms指向同一块内存 计数器=2
NSLog(@"%lu",(unsigned long)[ms retainCount]);//引用个数
[ms release];
NSLog(@"%lu",(unsigned long)[ms retainCount]);//引用个数
2022-05-18 14:47:20.811024+0800 OC02[2479:80125] 2
2022-05-18 14:47:20.812957+0800 OC02[2479:80125] 1
- (void)setName:(NSString *)_name{
if (_name!=name) {
[name release];
name=[_name retain];
}
name=_name;
}
//------------------------------
NSString * name=@"马富";//name的引用计数1
MFStudent * ms=[[MFStudent alloc]init];
[ms setName:name];//name的引用计数2
MFStudent * ms2=[[MFStudent alloc]init];
[ms2 setName:name];//name的引用计数3
NSLog(@"%lu",(unsigned long)[name retainCount]);//引用个数1
@interface MFStudent : NSObject
{
NSString * name;
}
-(void)setName:(NSString *)_name;
-(NSString *)name;
@end
@implementation MFStudent
-(void)dealloc{
NSLog(@"%@被销毁",name);
// [super dealloc];
}
- (void)setName:(NSString *)_name{
/*
if (_name!=name) {
[name release];
name=[_name retain];
}
*/
name=_name;
}
- (NSString *)name{
return name;
}
@end
MFStudent * mf=[[MFStudent alloc]init];
mf.name=@"麻烦";
NSLog(@"%@",mf.name);
通过一个属性关键字来替换上述过程:
@interface MFStudent : NSObject
/*
{
NSString * name;
}
-(void)setName:(NSString *)_name;
-(NSString *)name;
*/
//strong表示当前从另外一个字符串对它进行赋值的时候,会先将原先字符串保留一下,强引用
@property(strong,nonatomic) NSString * name;//相当于上述的属性命名和set,get函数声明
@end
@implementation MFStudent
-(void)dealloc{
NSLog(@"%@被销毁",name);
// [super dealloc];
}
/*
- (void)setName:(NSString *)_name{
//if (_name!=name) {
// [name release];
// name=[_name retain];
//}
name=_name;
}
- (NSString *)name{
return name;
}
*/
@synthesize name;//相当于实现了上述的set和get的行为
NSMutableString * name=[[NSMutableString alloc]initWithString:@"mafu"];
MFStudent * mf=[[MFStudent alloc]init];
mf.name=name;
NSLog(@"%@",mf.name);
MFStudent * mf2=[[MFStudent alloc]init];
mf2.name=name;
[name setString:@"lisi"];//name=@"lisi";
NSLog(@"%@",mf2.name);
//有两个对象同时使用了一个空间
2022-05-18 15:16:01.922824+0800 OC02[2703:90729] mafu
2022-05-18 15:16:01.924319+0800 OC02[2703:90729] lisi
2022-05-18 15:16:01.924582+0800 OC02[2703:90729] lisi被销毁
2022-05-18 15:16:01.924847+0800 OC02[2703:90729] lisi被销毁
@property(copy,nonatomic) NSString * name;//获取副本
2022-05-18 15:18:26.371787+0800 OC02[2719:91587] mafu
2022-05-18 15:18:26.372742+0800 OC02[2719:91587] mafu
2022-05-18 15:18:26.372916+0800 OC02[2719:91587] mafu被销毁
2022-05-18 15:18:26.372993+0800 OC02[2719:91587] mafu被销毁
shift+comand+alt+<-
AutoreleasePool
内存管理之AutoreleasePool:
//-----------------------------------
MFStudent * mf=[[MFStudent alloc]init];
[mf release];
//-----------------------------------
MFStudent * mf=[[MFStudent alloc]autorelease]
//-----------------------------------
NSString * str=[NSString stringWithFormat:@"%d",123]//调用类的行为包含了autorelease
str==[[NSSstring alloc]init]//普通对象行为,创建对象行为不包含autorelease
//-----------------------------------
NSString * str=@"ab"
NSString * str1=[str copy]
//-----------------------------------
//拷贝类需要实现一个协议
@interface MFStudent : NSObject<NSCopying>
@propery(retain) NSString * name;
//@propery(assign) NSString * name;//简单数据类型使用的是assign,而不是复制retain
@implementation
-(id)copyWithZone:(NSZone *)zone{
MFStudent * s=[[[self class]alloc]init];
s.name=name;
return s;
}
@synthesize name;
MFStudent * mf1=[[MFStudent alloc]init];
MFStudent * mf2=[mf1 copy];
Category
OC中的Category:类别,如何给已经有的类添加行为,而且该类是没有源代码的情况下。
//方法1:继承
//方法2:类别
//=======NSString+show.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface NSString (show)
-(void)show;
- (NSString *)trim;//
//[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
@end
NS_ASSUME_NONNULL_END
//=======NSString+show.m
#import "NSString+show.h"
@implementation NSString (show)
- (void)show{
NSLog(@"mafu");
}
- (NSString *)trim{
return [self stringByReplacingOccurrencesOfString:@" " withString:@""];
}
@end
//=======main.m
NSString * str=[NSString stringWithFormat:@"%d",12];
[str show];
有个这个类,想要在其他项目也能使用这个类?
//直接增加整个文件?? add file
类别只能添加行为,但也会覆盖行为。
新版xcode如何创建类别Category:新建oc文件
Protocol
OC中的协议Protocol:c中不允许多个继承,协议的话可以实现多个协议
//action.h 协议只有声明没有实现
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@protocol action <NSObject>
@required//必须实现的
-(void)say;
@optional//指定的,任意实现
-(void)song;
@end
NS_ASSUME_NONNULL_END
//action2.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@protocol action2 <NSObject>
-(void)walk;
@end
NS_ASSUME_NONNULL_END
#import <Foundation/Foundation.h>
#import "action.h"
NS_ASSUME_NONNULL_BEGIN
@interface Student : NSObject<action,action2>
@property(strong,nonatomic) NSString * name;
@end
NS_ASSUME_NONNULL_END
#import "Student.h"
@implementation Student
@synthesize name;//synthesize 合成
- (void)say{
NSLog(@"%@say!",name);
}
- (void)song{
NSLog(@"%@ song!",name);
}
- (void)walk{
NSLog(@"%@ walk",name);
}
@end
Student * s=[[Student alloc]init];
s.name=@"mafu";
[s say];
[s song];
NSCopying
OC中的NSCopying:协议的应用,保存副本
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface MFStudent2 : NSObject<NSCopying>
@property(strong,nonatomic) NSString * name;
@property(assign,nonatomic) int age;
-(void)say;
@end
NS_ASSUME_NONNULL_END
#import "MFStudent2.h"
@implementation MFStudent2
//@synthesize name,age;//后面可以不声明这个,_name
- (void)say{
NSLog(@"name=%@,age=%d",_name,_age);
}
- (nonnull id)copyWithZone:(nullable NSZone *)zone {
MFStudent2 * s=[[[self class]alloc]init];
s.name=_name;
s.age=_age;
return s;
}
- (NSString *)description
{
return [NSString stringWithFormat:@"name=%@,age=%d",_name,_age];
}
@end
NSString * str=@"1234";
NSString * str1=[str copy];//静态拷贝
NSLog(@"%@",str1);
MFStudent2 * s=[[MFStudent2 alloc]init];
s.name=@"mafu";
s.age=2;
[s say];
MFStudent2 * s2=[s copy];
NSLog(@"%@",s2);
File-Archive
OC的File-Archive:对文件进行操作:
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface MFStudent3 : NSObject<NSCoding>
@property(strong,nonatomic) NSString * name;
@property(assign,nonatomic) int age;
-(void)say;
@end
NS_ASSUME_NONNULL_END
#import "MFStudent3.h"
@implementation MFStudent3
- (void)say{
NSLog(@"name=%@,age=%d",_name,_age);
}
- (void)encodeWithCoder:(nonnull NSCoder *)coder {
[coder encodeObject:_name forKey:@"name"];
[coder encodeInt:_age forKey:@"age"];
}
- (nullable instancetype)initWithCoder:(nonnull NSCoder *)coder {
self=[super init];
_name=[coder decodeObjectForKey:@"name"];
_age=[coder decodeIntForKey:@"age"];
return self;
}
@end
NSString * str=@"123";
[str writeToFile:@"/Users/mafu/xcode_project/OC02/OC02/abc.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];
MFStudent3 * s1=[[MFStudent3 alloc]init];
s1.name=@"ma1";
s1.age=2;
MFStudent3 * s2=[[MFStudent3 alloc]init];
s2.name=@"ma2";
s2.age=4;
MFStudent3 * s3=[[MFStudent3 alloc]init];
s3.name=@"ma3";
s3.age=6;
NSArray * array=[NSArray arrayWithObjects:s1,s2,s3, nil];
for(MFStudent3 * s in array){
[s say];
}
NSLog(@"%d",[array writeToFile:@"/Users/mafu/xcode_project/OC02/OC02/abc.txt" atomically:YES]);//array写类失败,原因是没有归档,即序列化
//需要对类进行编码和解码
//还要基于关键字归档
NSLog(@"%d",[NSKeyedArchiver archiveRootObject:array toFile:@"/Users/mafu/xcode_project/OC02/OC02/abc.plist"]);
// [NSKeyedArchiver archivedDataWithRootObject:<#(nonnull id)#> requiringSecureCoding:<#(BOOL)#> error:<#(NSError *__autoreleasing _Nullable * _Nullable)#>]
NSArray * array=[NSKeyedUnarchiver unarchiveObjectWithFile:@"/Users/mafu/xcode_project/OC02/OC02/abc.plist"];
for(MFStudent3 * s in array){
[s say];
}
NSFileManager
OC中的NSFileManager:
NSFileManager * fm=[NSFileManager defaultManager];//单例
//判断一个文件是否存在
NSLog(@"%d",[fm fileExistsAtPath:@"/Users/mafu/xcode_project/OC02/OC02/abc.plist"]);
//拷贝或者删除一个文件
NSError * error;
NSLog(@"%d",[fm removeItemAtPath:@"/Users/mafu/xcode_project/OC02/OC02/abc.txt" error:&error]);
NSLog(@"%@",error);
NSLog(@"%d",[fm copyItemAtPath:@"/Users/mafu/xcode_project/OC02/OC02/abc.plist" toPath:@"/Users/mafu/xcode_project/OC02/OC02/abc2.plist" error:nil]);
//得到文件属性
NSDictionary * dic=[fm attributesOfItemAtPath:@"/Users/mafu/xcode_project/OC02/OC02/abc2.plist" error:nil];
NSLog(@"%@",dic);
NSPredicate
OC中的NSPredicate:谓词 用于集合过滤
NSMutableArray * str=[[NSMutableArray alloc]initWithCapacity:100];
// for (int i=0; i < 100; i++) {
// int a1=arc4random()%26+65;//产生大写字母
// int a2=arc4random()%26+65;
// int a3=arc4random()%26+65;
// int a4=arc4random()%26+65;
// int a5=arc4random()%26+65;
// [str addObject:[NSString stringWithFormat:@"%c%c%c%c%c",a1,a2,a3,a4,a5]];
// }
// for(NSString * s in str){
// if ([s hasPrefix:@"A"]) {
// NSLog(@"%@",s);
// }
// }
// [str addObject:@"abcd1"];
// [str addObject:@"bcd2"];
// [str addObject:@"bcd3"];
// [str addObject:@"abcd4"];
// //定制筛选条件 @"self='abcd3'" self like 'a?'
// NSPredicate * pre=[NSPredicate predicateWithFormat:@"self like 'a*'"];
// for(NSString * s in str){
// if ([pre evaluateWithObject:s]) {
// NSLog(@"%@",s);
// }
// }
MFStudent4 * stu1=[[MFStudent4 alloc]init];
stu1.name=@"张1";
stu1.age=12;
MFStudent4 * stu2=[[MFStudent4 alloc]init];
stu2.name=@"刘2";
stu2.age=13;
[str addObject:stu1];
[str addObject:stu2];//@"name like '刘*'"
NSPredicate * pre=[NSPredicate predicateWithFormat:@"age < 13"];
for(MFStudent4 * s in str){
if ([pre evaluateWithObject:s]) {
NSLog(@"%@",s);
}
}
Singleton
设计模式之单例Singleton:
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface MFUIapplication : NSObject
+(MFUIapplication *)shareAppliaction;
@end
NS_ASSUME_NONNULL_END
#import "MFUIapplication.h"
static MFUIapplication * application=nil;
@implementation MFUIapplication
+ (MFUIapplication *)shareAppliaction{
@synchronized(self) {
if (application==nil) {
application=[[[self class]alloc]init];
return application;
}
}
return application;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone{
@synchronized (self) {
if (application==nil) {
application=[super allocWithZone:zone];
return application;
}
}
return application;
}
@end
//单例:永远得到同一个对象
// MFStudent5 * a=[[MFStudent5 alloc]init];
// MFStudent5 * b=[[MFStudent5 alloc]init];
// NSUserDefaults * a=[NSUserDefaults standardUserDefaults];
// NSUserDefaults * b=[NSUserDefaults standardUserDefaults];
// MFUIapplication * a=[MFUIapplication shareAppliaction];
// MFUIapplication * b=[MFUIapplication shareAppliaction];
MFUIapplication * a=[[MFUIapplication alloc]init];//重写内存分配方法
MFUIapplication * b=[[MFUIapplication alloc]init];
if (a==b) {
NSLog(@"相同");
}
Delegate
设计模式之代理Delegate:
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface MFBoss : NSObject
@property (strong,nonatomic) NSString * name;
-(void)talk;
-(void)phone;
-(void)payoff;
@end
NS_ASSUME_NONNULL_END
#import "MFBoss.h"
@implementation MFBoss
- (void)talk{
NSLog(@"%@谈心",_name);
}
- (void)phone{
NSLog(@"%@电话",_name);
}
- (void)payoff{
NSLog(@"%@发钱",_name);
}
@end
MFBoss * b=[[MFBoss alloc]init];
b.name=@"ma";
[b talk];
[b phone];
[b payoff];
----秘书类代理
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@protocol SecDelegate <NSObject>
-(void)phone;
-(void)payoff;
@end
NS_ASSUME_NONNULL_END
#import <Foundation/Foundation.h>
#import "SecDelegate.h"
NS_ASSUME_NONNULL_BEGIN
@interface MFSec : NSObject<SecDelegate>
@property(strong,nonatomic)NSString * name;
@end
NS_ASSUME_NONNULL_END
//------------------------------------------
#import "MFSec.h"
@implementation MFSec
- (void)phone{
NSLog(@"%@电话",_name);
}
- (void)payoff{
NSLog(@"%@发钱",_name);
}
@end
#import <Foundation/Foundation.h>
#import "MFSec.h"
NS_ASSUME_NONNULL_BEGIN
@interface MFBoss : NSObject
@property (strong,nonatomic) NSString * name;
-(void)talk;
@end
NS_ASSUME_NONNULL_END
//-------------------------------
#import "MFBoss.h"
@implementation MFBoss
- (void)talk{
NSLog(@"%@谈心",_name);
}
/*
- (void)phone{
NSLog(@"%@电话",_name);
}
- (void)payoff{
NSLog(@"%@发钱",_name);
}
*/
@end
//--------------------------------
MFBoss * b=[[MFBoss alloc]init];
b.name=@"ma";
MFSec * sec=[[MFSec alloc]init];
sec.name=@"mei";
b.sec=sec;
[b talk];
[b.sec phone];
[b.sec payoff];
OC我的通讯录
OC我的通讯录1
//main.m
#import <Foundation/Foundation.h>
#import "MFMenu.h"
int main(int argc, const char * argv[]) {
// 添加,删除,修改,查找,显示,退出
@autoreleasepool {
MFMenu * menu=[[MFMenu alloc]init];
while (1) {
[menu show];
if ([menu input]) {
break;
}
}
}
return 0;
}
//MFMenu.h
#import <Foundation/Foundation.h>
#import "MFTel.h"
NS_ASSUME_NONNULL_BEGIN
@interface MFMenu : NSObject
@property(strong,nonatomic) NSArray * items;
@property(strong,nonatomic) MFTel * tel;//通讯录
-(void)show;
-(BOOL)input;
@end
NS_ASSUME_NONNULL_END
//MFMenu.m
#import "MFMenu.h"
@implementation MFMenu
- (instancetype)init
{
self = [super init];
if (self) {
self.items=[NSArray arrayWithObjects:@"增加",@"删除",@"修改",@"查找",@"显示",@"退出", nil];
self.tel=[[MFTel alloc]init];
}
return self;
}
@synthesize items,tel;
-(void)show{
int c=0;
for (NSString * s in items) {
c++;
printf("%d:%s\n",c,[s UTF8String]);
}
}
- (BOOL)input{
char ch[2];
printf("请输入:");
scanf("%s",ch);
ch[1]='\0';
if (strcmp(ch, "1")==0) {
if ([tel add]) {
printf("成功\n");
}else{
printf("失败\n");
}
}else if (strcmp(ch, "2")==0) {
if ([tel update]) {
printf("成功\n");
}else{
printf("失败\n");
}
[tel delete];
}else if(strcmp(ch, "3")==0) {
if ([tel update]) {
printf("成功\n");
}else{
printf("失败\n");
}
}else if(strcmp(ch, "4")==0) {
if ([tel find]) {
printf("成功\n");
}else{
printf("失败\n");
}
}else if(strcmp(ch, "5")==0) {
[tel showALl];
}else if(strcmp(ch, "6")==0) {
printf("退出:\n");
return YES;
}else{
printf("输入错误!\n");
}
return NO;
}
@end
//MFTel.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface MFTel : NSObject
@property(strong,nonatomic) NSMutableArray * persons;
-(BOOL)add;
-(BOOL)delete;
-(BOOL)update;
-(BOOL)find;
-(void)showALl;
@end
NS_ASSUME_NONNULL_END
//MFTel.m
#import "MFTel.h"
#import "MFPerson.h"
@implementation MFTel
@synthesize persons;
- (instancetype)init
{
self = [super init];
if (self) {//读取磁盘联系人
persons=[NSKeyedUnarchiver unarchiveObjectWithFile:@"/Users/mafu/xcode_project/OC15通讯录/OC15通讯录/telbook.plist"];
if (persons==nil) {
persons=[NSMutableArray arrayWithCapacity:100];
}
}
return self;
}
- (BOOL)add{
printf("增加联系人:\n");
char ch[20];
MFPerson * p=[[MFPerson alloc]init];
printf("姓名:");
scanf("%s",ch);
ch[19]='\0';
p.name=[NSString stringWithUTF8String:ch];
printf("电话:");
scanf("%s",ch);
ch[19]='\0';
p.phone=[NSString stringWithUTF8String:ch];
[persons addObject:p];
[NSKeyedArchiver archiveRootObject: persons toFile:@"/Users/mafu/xcode_project/OC15通讯录/OC15通讯录/telbook.plist"];
;
return YES;
}
- (BOOL)delete{
printf("删除联系人:\n");
printf("输入编号:");
char ch[4];
scanf("%s",ch);
ch[3]='\0';
int n=atoi(ch);
if (n>persons.count) {
printf("不存在此人!\n");
return NO;
}
[persons removeObjectAtIndex:n-1];
//文件需要代码创建,自己手动创建的是无效的
[NSKeyedArchiver archiveRootObject: persons toFile:@"/Users/mafu/xcode_project/OC15通讯录/OC15通讯录/telbook.plist"];
return YES;
}
- (BOOL)update{
printf("修改联系人:\n");
printf("输入编号:");
char ch1[4];
scanf("%s",ch1);
ch1[3]='\0';
int n=atoi(ch1);
if (n>persons.count) {
printf("不存在此人!\n");
return NO;
}
//[persons removeObjectAtIndex:n-1];
char ch[20];
MFPerson * p=[[MFPerson alloc]init];
printf("姓名:");
scanf("%s",ch);
ch[19]='\0';
p.name=[NSString stringWithUTF8String:ch];
printf("电话:");
scanf("%s",ch);
ch[19]='\0';
p.phone=[NSString stringWithUTF8String:ch];
persons[n-1]=p;
[NSKeyedArchiver archiveRootObject: persons toFile:@"/Users/mafu/xcode_project/OC15通讯录/OC15通讯录/telbook.plist"];
return YES;
}
- (BOOL)find{
printf("查找联系人:\n");
char ch[20];
MFPerson * p=[[MFPerson alloc]init];
printf("姓名:");
scanf("%s",ch);
ch[19]='\0';
NSString * str=[NSString stringWithUTF8String:ch];
BOOL b=NO;
for (MFPerson * p in persons) {
if([p.name isEqualToString:str]||[p.phone isEqualToString:str]){
printf("编号\t姓名\t电话\n");
for(MFPerson * p in persons){
printf("name=%s\tphone=%s\n",[p.name UTF8String],[p.phone UTF8String]);
}
b=YES;
}
}
return b;
}
- (void)showALl{
printf("显示所有联系人:\n");
if (persons.count==0) {
printf("没有联系人\n");
}else{
int c=0;
printf("编号\t姓名\t电话\n");
for(MFPerson * p in persons){
printf("id=%d\tname=%s\tphone=%s\n",++c,[p.name UTF8String],[p.phone UTF8String]);
}
}
}
@end
//MFPerson.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface MFPerson : NSObject<NSCoding>//要想将人保存在磁盘就得需要实现序列化
@property(strong,nonatomic) NSString * name;
@property(strong,nonatomic) NSString * phone;
@end
NS_ASSUME_NONNULL_END
//MFPerson.m
#import "MFPerson.h"
@implementation MFPerson
@synthesize name,phone;
- (void)encodeWithCoder:(NSCoder *)coder
{
[coder encodeObject:name forKey:@"NAME"];
[coder encodeObject:phone forKey:@"PHONE"];
}
- (nullable instancetype)initWithCoder:(nonnull NSCoder *)coder {
self=[super init];
name=[coder decodeObjectForKey:@"NAME"];
phone=[coder decodeObjectForKey:@"PHONE"];
return self;
}
@end
Xcode
Xcode开发界面。
界面和分离开。
纯代码版,极速版。
//程序代理类
AppDelegate.h
AppDelegate.m
//屏幕代理类
SceneDelegate.h
SceneDelegate.m
//视图控制器类
ViewController.h
ViewController.m
//Main故事板
Main.storyboard
//发射屏幕故事板
LaunchScreen.storyboard
//主函数
main.m
//Info.plist
//1、删除移动项 2、手动创建窗口
删除主接口,删除三个文件:
//视图控制器类
ViewController.h
ViewController.m
//Main故事板
Main.storyboard
self.window=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
self.window.rootViewController=rootVC;
[self.window makeKeyAndVisible];
Application
17-21章
Application生命周期:
应用程序的事件由应用程序的代理类来处理。前台,后台,didFinishLaunchingWithOptions系统调用。applicationWillResignActive将要进入后台,保存当前状态。applicationDidEnterBackground,释放资源在进入后台后暂停。applicationWillEnterForeground将要进入前台。applicationDidBecomActive进入前台。applicationWillTerminate将要终止退出。
UIWindow
属性方法:是一个容器
//创建应用程序对象
UIApplication,AppDelegate;
//应用程序发射完成,系统调用,创建一个窗口对象,和手机屏幕一样大
UIScreen mainScreen bounds产生
Frame就是一个CGRect,本控件自己相对父控件的位置
bounds区别于Frame的地方在于bounds永远起始坐标都是00
window.backgroundColor UIColor whiteColor
window.key makeKeyAndVisible显示窗口
Icon图标和Launchimage启动图片设置。
ViewController * vc=[[ViewController alloc]init];
self.window=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
self.window.rootViewController=vc;
UIView * v=[[UIView alloc]initWithFrame:CGRectMake(10, 20, 200, 300)];
v.backgroundColor=[UIColor redColor];
UIView * vv=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
vv.backgroundColor=[UIColor greenColor];
[v addSubview:vv];
[self.window addSubview:v];
ios8启动图片icon和图标的改动-更新
LaunchScreen.storyboard启动界面
UILabel
属性方法:UIButton的属性方法:
UILabel * label=[[UILabel alloc]initWithFram:CGRecMake(10,30,200,30)];
[label setText:@"xxxx"];
[label setBackgroundColor:[UIColor redColor]];
[label setTextColor:[UIColor greenColor]];
[self.window addSubview:label];
//UIButonTypeCustom 指定图片背景
//[bten setImage:[UIImage imageNamed:@"xx.png"] forState:UIControlStateNormal]
UIButton * btn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn setTrame:CGRectMake(0,20,100,100,50)];
//[btn setBackgroundColor:[UIColor redColor]];
btn.backgroundColor=[UIColor redColor]
[btn setTitle:@"确定",forState:UIControlStateNormal];
[btn addTarget:self action:@selector(buttonTap:) forControlEvents:UIControlEventTouchUpInside];
[self.window addSubview:btn];
//-(void)buttonTap:(id)sender{
// NSLog(@"按钮被单击了");
//}
-(void)buttonTap:(UIButton *)sender{
UIButton *btn=sender;
NSLog(@"按钮被单击了 %@",btn.titel);
}
22章计算器
项目界面分析:界面按钮尺寸计算:
//调节状态栏的颜色,状态栏宽度20固定。点亮式
self.window=[[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
self.window.backgroundColor=[UIColor blackColor];
[sel createLabel];
[self.window makeKeyAndVisible];
msg=[NSMutableString stringWithCapactiy:20];
permsg=[[NSString alloc]init];
strsign=[[NSString alloc]init];
@interface AppDelegate:UIResponder<UIApplicationDelegate>{
UILabel * lblMessage;
NSMutableString * msg;//标签显示的文本
NSSstring * permsg;
NSString * strsign;
}
@property(strong,nonatomic)UIWindow *window;
-(void)createLabel{
//UILabel * lblMessage=[[UILabel alloc]initWithFrame:CGRectMake(0,20,320,60)];
lblMessage=[[UILabel alloc]initWithFrame:CGRectMake(0,20,320,60)];
lblMessage.textAligment=NSTextAlignmentRight;
//[UIFont fontWithName:@"黑体",size:72];
lblMessage.font=[UIFont systemFontOfSize:40];
lblMessage.textColor=[UIColor whiteColor];
lblMessage.txt=@"0";
//创建计算器按钮
[self crateButtons];
[self.window addSubview:lblMessage];
}
-(void) createButtons{
/*
UIButton * btnClear=[[UIButton alloc]initWithFrame:CGRectMake(0,80,80,80)];
btnClear.backgoundColor=[UIColor grayColor];
[btnClear setTitle=@"C"];
[self.window addSubview:btnClear];//背景颜色默认透明
UIButton * btnSign=[[UIButton alloc]initWithFrame:CGRectMake(80,80,80,80)];
btnSign.backgoundColor=[UIColor grayColor];
[btnSign setTitle=@"+/-"];
[self.window addSubview:btnSign];
*/
NSArray * title=[NSArray arrayWithObjects:@"C",@"+/-",@"%",@"/",@"7",@"8", @"9",@"x", @"4",@"5", @"6",@"-",@"1",@"2", @"3",@"+", @"0",@"", @".",@"=",nil];
//(number:)表示带一个参数
SEL actions[20]={@selector(clear),@selector(siging),@selector(mod),
@selector(sign:),@selector(number:),@selector(number:),
@selector(number:),@selector(sign),@selector(number:),
@selector(number:),@selector(number:),@selector(sign),
@selector(number:),@selector(number:),@selector(number:),
@selector(sign),@selector(zero),@selector(number:),
@selector(dot),@selector(equal)};
for(int i=0;i<5;i++){
for(int j=0;j<4;j++){
UIButton * btn=[[UIButton alloc]initWithFrame:CGRectMake(80*j,80*i,79,79)];
if(i==4&&j==0) [btn setFrame:CGRectMake(80*j,80*i,159,79)];
if(i==4&&j==1) [btn setFrame:CGRectMake(80*j,80*i,0,0)];
if(i==0) btn.backgoundColor=[UIColor grayColor];
else btn.backgoundColor=[UIColor lightGrayColor];
if(j==3) btn.backgoundColor=[UIColor OrangeColor];
[btn setTitle:titles[i*4+j] forState:UIControlStateNormal];
[btn addTarget:self action:actions[i*4+j] forControlEvens:UIControlEventTounchUpTap];
[self.window addSubview:btn];
}
}
}
-(void)clear{
NSRange rane={0,msg.length};
[msg delteCharactersInRange:range];//msg=@"";静态字符串后续无法改变
lblMessage.text=@"0";
}
-(void)siging{//正负号
if(msg.length==0) return;//防止下面的提取第一个坐标数组越界报错
if([msg characterAtIndex:0]=='-'){
NSRange range={0,1};
msg=[msg replaceCharactersInRange:range withString:@""];
lblMessage.txt=msg;
}else{
NSString * str=[NSString stringWithFrom:@"-%@",msg];
[msg setString:str];
lblMessage.txt=msg;
}
}
-(void)mod{//百分号
double d=[msg doubleValue];
d=d/100.0;
[msg setString:[NSString stringWithFormat:@"%d",d]];
lblMessage.txt=msg;
}
-(void)sign:(UIButton *)sender{//加减乘除
// permsg=msg;
permsg=[msg copy];//必须要是拷贝,不能用引用
[msg setString:@""];
strsign=sender.titleLabel.text;
}
-(void)number:(UIButton *)sender{
[msg appendString:sender.titlebel.text];//连接字符串
lblMessage.text=msg;
}
-(void)dot{
if(msg.length==0) {
[msg appendString:@"0."];
lblMessage.text=msg;
return;
}
[msg appendString:@"."];
lblMessage.text=msg;
}
-(void)zero{
//判断第一次点击是否为0
NSRange range=[msg rangeOfString:@"."];
if(msg.length==0||range.loacation==NSNotFound) return;
[msg appendString:@"0"];
lblMessage.text=msg;
}
-(void)equal{
double pre=[premsg doubleValue];
double cur=[msg doubleValue];
double sum=0.0;
if([strsign isEqualToString:@"+"]) sum=pre+cur;
else if([strsign isEqualToString:@"-"]) sum=pre-cur;
else if([strsign isEqualToString:@"x"]) sum=pre*cur;
else([strsign isEqualToString:@"/"]) sum=pre/cur;
NSString str=[NSString stringWithFormat:@"%g",sum];
lblMessage.text=str;
[msg setString:@""];
}//没有实现连加连减功能
23-38章
UITextField
属性和方法:
@interface
{
UITextFiled * text;
UITextView * tv;
}
//文本框是一个既可以输入也可以输出的控件,但输出一般用标签
//只接收单行文本
text=[[UIText alloc]initWithFrame:CGRectMake(10,40,100,50)];
text.backgroundcolor[UIColor buleColor];
text.textColor=[UIColor greenColor];
//text.text=@"xxxxx";
text.textAlignment=NSTextAlignmentCenter;
//指定输入键盘
text.keyboardType=UIKeyboardTypePhonePad;//UIKeyboardTypeNumberPad;
//设定return按钮显示文本
text.returnKeyType=UIKeturnDone;
//提示信息,对齐方式取决于文本属性
text.placeholder=@"请输入";
//设定密码
text.secureTextEntry=YES;
//多行文本框
tv=[[UITextView alloc]initWithFram:CGRectMake(10,100,200,50)];
tv.text=@"xxx\nxx";
UIButtton * btn=[[UIButton alloc]initWithFrame:CGRectMake()220,40,100,50];
[btn setTitle:@"确定" forState:UIControlStateNormal];
btn.backgroundColor=[UIColor blackColor];
//btn.titleLabel.textColor=[UIColor redColor];
[btn addTarget:self action:@selector(okTap:) forControlEvents:UIControlEventTouchUpInSide];
[self.window addSubView:btn];
[self.window addSubView:tv];
[self.window addSubview:text];
-(void)okTap:(id)sender{
NSLog(@"this is oktap!内容:%@,%@",text.text.tv.text);
}
@interface
{
UITextFiled * number;//不想对外访问就定义为成员变量,否则就定位属性@property
}
//文本框应用
number=[[UITextFiled alloc]initWithFrame:CGRectMake(10,30,200,40)];
number.backgroundcolor=[UIColor blcakColor];
number.textColor=[UIColor whiteColor];
number.keyboardType=UIKeyboardYtpeNumberPad;
UIButton * sum=[[UIButton alloc]initWhitFrame:CGRectMake(60,90,200,50)];
sum.backgroundColor=[UIColor redColor];
[sum setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
[sum setTitle:@"相加" forState:UIControlStateNormal];
[sum addTarget:self action:@selecto(sumTap:) forControlEventTouchUpInside];
[self.window addSubview:sum];
[self.window addSubview:number];
[self.window makeKeyAndVisible];
-(void)sumTap:(UIButton *)sender{
NSString * strNUmber=number.text;
//数据有效性验证
if(strNumber.length==0) {
//警报,消息对话框
UIAlertView * alert=[[UIAlertView]initWithTitle:@"友情提示" message@"数字不为空" delegate:nil cancelButtonTitle:@"我知道了",otherButtonTitles:nil,nil];
[alert show];
return;
}
int num=[strNumber intValue];
int s=0;
for(int i=1;i<=num;i++) s+=i;
number.text=[NSString stringWithFormat:@"%d",s];
}
ios8 UItextFiled输入框键盘弹出问题。
UISwitch
属性和方法:开关控件
UISwitch * s=[[UISwitch alloc]initWithcFrame:CGRectMake(10,30,50,50)];//宽度和固定
//状态转换,参数可以将事件源给带回来
[s addTarget:self action:@selector(switchChange:) forControlEvents:UIControlEventValueChanged];
[self.window addSubView:s];
//区分的方式
s.tag=10;
UISwitch * s2=[[UISwitch alloc]initWithcFrame:CGRectMake(80,30,50,50)];//宽度和固定
//状态转换,参数可以将事件源给带回来
[s2 addTarget:self action:@selector(switchChange:) forControlEvents:UIControlEventValueChanged];
s.on=YES;
s2.on=YES;
s2.tag=20;
[self.window addSubView:s2];
[self.window makeKeyAndVisble];
-(void)switchChange:(UISwitch *)sender{
// NSLog(@"改变了");
BOOL b=sender.on;
//新的技术:通过tag获取视图
UISwitch * s=(UISwitch *)[self.window viewWithTag:10];
UISwitch * s2=(UISwitch *)[self.window viewWithTag:20];
//同时转换
s.on=b;
s2.on=b;
if(b) NSLog(@"打开了");
}
UISegmentedControl
属性和方法:分段控件
@interface
{
UILabel * label;
}
//-----------
NSArray * items=[NSArray arrayWithObjects:@"one",@"two",@"three",nil];
UISegmentedControl * sc=[[UISegmentedControl alloc]initWithItems:items];
sc.frame=CGRectMake(10,40,100,40);
sc.backgroundColor=[UIColor redColor];
[sc addTarget:self action:@selector(segchange)
forControlEvents:UIControlEventValueChanged];
[sc setImgae:[UIImgae imageNamed:"@a.png"] forSegmentAtIndex:2];
[self.window addSubview:sc];
label=[[UILabel alloc]initWithcFrame:CGRecMake(220,40,600,40)];
[label setBackgroundColor:[UIColor redColor]];
[sc setSelectedSegmentIndex:0];
label.text=@"one";
[self.window addSubview:label];
[self.window makeKeyAndVisible];
-(void)segChange:(UISegmentedControl *)sender
{
//NSLog(@"@%d",[sender selectedSegmentIndex]);
label.text=[sender titleForSegmentAtIndex:[sender selectedSegmentIndex]];
}
UISlider
属性和方法:滑块控件
@interface
{
UITextFiled * text;
}
//------
UISlider * slider=[[UISlider alloc]initWithFrame:CGRectMake(10,30,200,50)];
[slider setMinimumValue:1];
[slider setMaximumValue:20];
[slider setValue:10];
[slider addTarget:self action:@selector(sliderChange:) forControlEvents:UIControlEentValueChanged];
text=[[UITextFiled alloc]initWithFrame:CGRectMake(220,30,80,50)];
text.backgroundColor=[UIColor bludColor];
text.enabled=NO;//不显示键盘
text.textAligment=NSTextAlignmentCenter;
text.text=@"20";
[self.window addSubview:text];
[self.window addSubview:slider];
[self.window makeKeyAndVisible];
-(void)sliderChange:(UISlider * )sender{
// NSLog(@"value=%g",sender.value);
text.text=[NSString stringWithFormat:@"%d",(int)sender.value;
}
UIProgressView
属性和方法:进度控件
@interface
{
UIProgressView * prog;
BOOL flag;
}
//-----
prog=[[UIProgressView alloc]initWithFrame:CGRectMake(0,40,320,50)];
prog.progress=0.0;
prog.trackTintColor=[UIColor blackColor];
prog.progressTintColor[UIColor redColor];
[self.window addSubview:prog];
UIButton * btn=[[UIButton alloc]initWithFrame:CGRectMake(0,100,320,40)];
[btn setTitle:@"走俩" forState:UIControlNormal];
btn.backgroundColor=[UIColor greenColor];
[self.window addSubview:btn];
[btn setTarget:self action:@selector(walkTap)forControlEvents:UIControlEventsTouchInSide];
flag=NO;//还没有到头
[self.window makeKeyAndVisible];
-(void)walkTap{
if(!flag) prog.progress+=0.1;
else prog.progress-=0.1;
if(prog.progress>=1.0) flag=YES;
if(prog.progress<=0.0) flag=NO;
}
UIActivityIndicatorView
活动指示器视图 ,仪表盘
@interface
{
UIActivityIndicatorView * aiv;
}
//---
aiv=[[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(50,50,100,50)];
//[aiv satrtAnimating];//开启动画,
aiv.heidesWhenStopped=NO;//因为要活动的时候才会显示
aiv.color=[UIColor blackColor];
aiv.backgroundColor=[UIColor yellowColor];
//aiv.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
aiv.activityIndicatorViewStyle=UIActivityIndicatorViewStyleLarge;//大白色
UIButton * b1=[[UIButton alloc]initWithFrame:CGRectMake(50,150,100,50)];
UIButton * b2=[[UIButton alloc]initWithFrame:CGRectMake(50,150,100,50)];
[b1 setTitle:@"启动" forState:UIControlNormal];
[b2 setTitle:@"停止" forState:UIControlNormal];
[b1 addTarget:self action:@selector(startTap) forControlEvents:UIControlEventTouchUpInSide];
[b2 addTarget:self action:@selector(stopTap) forControlEvents:UIControlEventTouchUpInSide];
[self.window addSubview:btn1];
[self.window addSubview:btn2];
[self.window addSubview:aiv];
[self.window makeKeyAndVisible];
-(void)startTap{
[aiv startAnimating];
}
-(void)stopTap{
[aiv stopAnimating];
}
UIImageView
图片视图
@interface
{
BOOL flag;
UIImgaeView * iv;
}
//----
iv=[[UIImgaeView alloc]initWithFrame:CGRectMake(0,20,160,240)];
//图片视图对象用来显示图片
//UIImage * img=[UIImage imageName:@"a.png"];//用到了缓存,小图片
NSString * path=[[NSBundle mainBundle] pathForResource:@"a" ofType:@"png"];//用时加载,不使用缓存
UIImage * img=[UIImage imageWithContentsOfFile:path];
[iv setImage:img];
[self.window addSubview:iv];
UIButton * btn=[[UIButton alloc]initWithFrame:CGRectMake(170,120,100,50)];
btn.backgroundColor=[UIColor greenColor];
[btn setTitle:@"切换",forState:UIControlStateNormal];
[btn addTarget:self action@selector(swapTap)
forControlEvents:UIControlEventTouchUpInside];
[self.window addSubview:btn];
[self.window makeKeyAndVisible];
-(void)swapTap{
if(flag==NO){
UIImage * imge=[UIImage imageNamed:@"logo.png"];
[iv setImage:img];
flag=YES;
}
else{
UIImage * imge=[UIImage imageNamed:@"b.png"];
[iv setImage:img];
flag=NO;
}
}
UIDatePicker
属性与方法:时间日期选择器控件
@interface
{
UIDatePicker * dp;
}
//---
dp=[[UIDatePicker alloc]initWithFrame:CGRectMake(0,20,320,200)];
dp.locale=[NSlocale localeWithLocaleIdentifier:@"zh-Hans"];
//dp.datePickerMode=UIDatePickerModeCountDownTimer倒计时 //设置时间模式
UIButton * btn=[[UIButton alloc]initWithFrame:CGRectMake(140,220,40,40)];
[btn setBackgroundColor:[UIColor greeenColor]];
[btn setTitle@"获得时间" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(getTimeTap) forControlEvents:UIControlEventTouchUpInSide];
[self.window addSubview:btn];
[self.window addSubview:dp];
[self.window makeKeyAndVisible];
-(void)getTimeTap{
NSDate * date=dp.date;
NSDateFormatter * frm=[[NSDateFormatter alloc]init];//时间日期格式
[frm setDateFormat:@"yyyy-MM-dd hh:mm:ss"];//"yyyy-MM-dd HH:mm:ss"24小时
NSString * str=[frm stringFromDate:date];
NSLog(@"%@",str);
}
UIPickerView
自定义选择器视图:
@interface AppDelegate:UIResponder<UIApplicationDelegate,UIPickerViewDataSource,UIPicekerViewDelegate>
@property(strong,nonatomic)NSArray * strings;
@property(strong,nonatomic)NSArray * strings2;
@proterty(strong,nonatomic)NSArray * images;
//-----------
self.strings=[NSArray arrayWithObjects:@"a",@"b",@"n",@"d",@"x",nil];
self.strings2=[NSArray arrayWithObjects:@"a2",@"b2",@"n2",nil];
self.iamges=[NSArray arrayWithObjects:[UIImage imageNamed:@"p1.png"],[UIImage imageNamed:@"p2.png"],[UIImage imageNamed:@"p3.png"]];
UIPickerView * myPicker=[[UIPickerView alloc]initWithFrame:CGRectMake(0,20,320,20)];
myPicker.delegate=self;//需要实现一个代理,设置选择器对象的代理类
mypicker.backgroundColor=[UIColor greenColor];
[myPicker selectRow:2 inCompoment:0 animated:YES];
[myPicker selectRow:2 inCompoment:1 animated:YES];
[self.window addSubView:myPicker];
[self.window makeKeyAndVisible];
//选择器显示数据时访问它 确定显示多少列
-(NSInteger)numberOfComponetnsInPickerView:(UIPickerView *)
{
//return 1;//本选择器之显示1列
return 2;
}
//选择器显示数据时访问它,确定显示多少行
-(NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component
{
//NSLog(@"%d",component);
//return 10;
if(component==0) return [self.strings count];
else return [self.strings2 count];
}
-(NSStirng * )pickerView:(UIPickerView *)pickerView titleForRow:
(NSInteger) row forCOmponent:(NSInteger)component
{
//return @"看到了";
return self.strings[row];
}
//修改前景颜色
//选择器显示数据时访问它 确定显示多少列
-(NSInteger)numberOfComponetnsInPickerView:(UIPickerView *)
{
return 1;//本选择器之显示1列
}
//选择器显示数据时访问它,确定显示多少行
-(NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component
{
//NSLog(@"%d",component);
//return 10;
return [self.strings count];
// return [self.images count];
}
//到哪列Component的哪行row 要显示的字符串
-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponern:(NSInterger)Component resingView:(UIView *)view
{
UILabel * label=[[UILabel alloc]initWithFrame:CGRectMake(0,0,320,50)];
label.textAlignment=NSTextAlignmentCenter;
label.text=self.stirngs[row];
label.textColor=[UIColor redColor];
return label;
/*
UIImageView * iv=[[UIImgaeView alloc]init];
[iv setImage:self.images[row]];
return iv;
*/
}
-(void)pickerView(UIPickerView *)pickerView didSlectRow:(NSInteger)row inComponent:(NSInteger)component{
if(component==0)
NSLog(@"你选择了:%@",self.strings[row]);
else
NSLog(@"你选择了:%@",self.strings[row]);
}
//设定选择器行高度的行为
-(CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponern:(NSInteger)component
{
return 100;
}
UIAlerTtView与UIActionSheet
警报和操作表:一般提示用户用警报,询问用户确认时候用操作表
@interface AppDelegate:UIResponder<UIApplicationDelegate,UIAlerViewDelegate,UIActionSheetDeleagte>
//---
UIButton * b1=[[UIButton alloc]initWithFrame:CGRectMake(0,50,150,50)];
b1.backgroundColor=[UIColor blackColor];
[b1 setTitle:@"警报" forState:UIControlStateNormal];
[b1 addTarger:self action:@selector(alerTap:) forControlEventTouchUpInside];
[self.window addSubView:b1];
UIButton * b2=[[UIButton alloc]initWithFrame:CGRectMake(170,50,150,50)];
b2.backgroundColor=[UIColor blackColor];
[b2 setTitle:@"操作表" forState:UIControlStateNormal];
[b2 addTarger:self action:@selector(actionTap:) forControlEventTouchUpInside];
[self.window addSubView:b2];
[self.window makeKeyAndVisible];
-(void)alerTap:(id)sender{
//模态视图,显示之后其他操作做不了
UIAlerView * alert=[[UIAlerView alloc]initWithTitle:@"标题" message:@"消息" delegate:self cancelButtonTitle:@"取消按钮标题" otherButtonTitles:@"其他按钮标题" ,nil];
[alert show];
}
-(void)actionTap:(id)sender{
UIActionSheet * as=[[UIActionSheet alloc]]initWithTitle:@"确认删除" delegate:self cancelButtonTitle:@"是" destructiveButonTitle:@"否" otherButttonTitles:@"取消",nil];
[as shoInView:self.window];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInterger)buttonIndex{
if(buttonIndex==0){
NSLog(@"你选中了是的按钮");
}
else if(buttonIndex==1){
NSLog(@"你选中了否的按钮");
}
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickeedButtonAtIndex:(NSInterger)buttonIndex
{
NSLog(@"%d",buttonIndex);
}
ios8的警报和操作表
@interface AppDelegate:UIResponder<UIApplicationDelegate,UIAlerViewDelegate,UIActionSheetDeleagte>
//---
UIButton * b1=[[UIButton alloc]initWithFrame:CGRectMake(0,50,150,50)];
b1.backgroundColor=[UIColor blackColor];
[b1 setTitle:@"警报" forState:UIControlStateNormal];
[b1 addTarger:self action:@selector(alertTap:) forControlEventTouchUpInside];//TouchUpInside单击事件
[self.window addSubView:b1];
UIButton * b2=[[UIButton alloc]initWithFrame:CGRectMake(170,50,150,50)];
b2.backgroundColor=[UIColor blackColor];
[b2 setTitle:@"操作表" forState:UIControlStateNormal];
[b2 addTarger:self action:@selector(actionTap:) forControlEventTouchUpInside];
[self.window addSubView:b2];
[self.window makeKeyAndVisible];
-(void)alertTap:(id)sender{
/*旧
UIAlerView * alert=[[UIAlerView alloc]initWithTitle:@"友情提示" message:@"xxxx" delegate:self cancelButtonTitle:@"知道" otherButtonTitles:nil ,nil];
[alert show];
*/
//新
UIAlerController * alert=[UIAlerCOntroller alertControlerWithTitle:@"友情提示" message:@"xxxx" perferredStyle:UIAlerControllerStyleAlertCancel];
UIAlertAction * cancleButton=[UIAlerAction actionWithTitle:@"知道" stytle:UIAlertActionSytle handler:^(UIAlertAction *){
NSLog(@"取消了");//这样新的就不用使用代理了
}]
[self presentViewController:aler animated:YES completion:nil ];
}
-(void)actionTap:(id)sender{
UIActionSheet * as=[[UIActionSheet alloc]]initWithTitle:@"确认删除" delegate:self cancelButtonTitle:@"是" destructiveButonTitle:@"否" otherButttonTitles:@"取消",nil];
[as shoInView:self.window];
}
UIAlerController
ios9的消息提示控制器
viewController.m
-(void)viewDiLoad{
[super viewDidLoad];
UIButton * alertButton=[[UIButton alloc]initWithFrame:CGRectMake(50,50,self.view.frame.size.width-50-50,,40)];
alertButton.backgroundColor=[UIColor blackColor];
[alertButton setTitleColor:[UIColor redColor]forState:UIControlSateNormal];
[alertButton setTile:@"警报" forState:UIControlStateNormal];
[alertButton addTarget:self action:@selecto(alertTap:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:alertButton];
UIButton * actionSheetButton=[[UIButton alloc]initWithFrame:CGRectMake(50,150,self.view.frame.size.width-50-50,,40)];
actionSheetButton.backgroundColor=[UIColor blackColor];
[actionSheetButton setTitleColor:[UIColor redColor]forState:UIControlSateNormal];
[actionSheetButton setTile:@"操作表" forState:UIControlStateNormal];
[actionSheetButton addTarget:self action:@selecto(actionTap:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:actionSheetButton];
}
-(void)alertTap:(UIButton *)sender{
// NSLog(@"this is alert!");
UIAlertControl * alert=[UIAlertController alertControllerWithTitle:@"标题"message:@"消息"perferredStyle:UIAlertControllerStyleAlert];
//action
UIAlertAction * cancel=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionSytleCancel handler:^(UIAlerAction * _Nonnull action){
NSLog(@"取消");
}];
UIAlertAction * ok=[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionSytleDefault handler:^(UIAlerAction * _Nonnull action){
NSLog(@"确定");
}];//处理事件变得简单一些
[alert addAction:cancle];
[alert addAction:ok];
[self persentViewController:alertController animated:YES completion:nill];
}
-(void)actionTap:(UIButton *)sender{
UIAlertControl * alert=[UIAlertController alertControllerWithTitle:@"标题"message:@"消息"perferredStyle:UIAlertControllerStyleActionSheet];
//action
UIAlertAction * cancel=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionSytleCancel handler:^(UIAlerAction * _Nonnull action){
NSLog(@"取消");
}];
UIAlertAction * ok=[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionSytleDefault handler:^(UIAlerAction * _Nonnull action){
NSLog(@"确定");
}];//处理事件变得简单一些
[alert addAction:cancle];
[alert addAction:ok];
[self persentViewController:alertController animated:YES completion:nill];
}
UIStackView
ios9的叠加视图
//ios7之后不能直接使用window了,window上面必须要有一个根的视图控制器
//自定义RootViewController 实现ViewController
@implementation RootViewController
-(void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor=[UIColor whiteColor];
//叠加视图
UIStackView * stackView=[[UIStackView alloc]initWithFrame:CGRectMake(50,50,50,100)];
//不能添加颜色,永远是透明的容器
//设置摆放方向
stackView.axis=UILayoutCOnstraintAxisVertical;//水平Horizontal
//对齐方式
stackView.alignment=UIStackViewAlignmentLeading;//首对齐
//分布方式
stackView.distribution=UIStackViewDistributionEqualCentering;
UIView * v=[[UIView alloc]initWhithFrame:CGReckMake(50,50,50,100)];
v.backgrounColor=[UIColor yellowColor];
//放到容器的东西自动布局和摆放
UIImageView * iv1=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"a.ong"]];
[stackView addArrangeSubview:iv1];
UIImageView * iv2=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"a.ong"]];
[stackView addArrangeSubview:iv2];
[self.view addSubview:stacView];
}
//AppDelegate.m
#import "RootViewController.h"
-(BOOL)application:(UIApplication *)appliaction didFinishLaunchingWithOptions:(NSDictionary * )launchOptions{
self.window=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
RootViewController * rootVC=[[RootViewController alloc]init];
self.window.rootViewController=rootVC;
[self.window makeKeyAndVisible];
return YES;
}
UIViewController
//前面做应用的时候,把所有的界面都是放在window上,然后用程序代理处理所有的事件
//随着程序越来越复杂将会有很多界面和控件
//以后设计中提供了一种解决方案:视图控制器UIViewController
//AppDelegate.h
#import "MainViewController.h"
MainViewController * main=[[MainViewControler alloc]init]//创建视图控制器
self.window.rootViewCOntroller=main;
//[self.window addSubview:main.view];
[self.window makeKeyWithVisibel];
//MainViewController 继承ViewController
//视图控制器作用,用来建立视图核和管理视图,管理视图以及视图上子视图事件
//初始化 (instancetype)initWithNibName
#import "OtherViewController.h"
//加载视图到内存,不需要重写
/*
-(void)loadView{}
*/
//视图加载到内存完成
-(void)viewDidLoad{
[super viewOidLoad];
self.viewbackgroundColor=[UIColorgreenColor];
UIButton * btn=[[UIButton alloc]initWithFrame:CGRectMake(0,50,100,50)];
[btn setTitle:@"显示" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(showTap:)forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
-(void)showTap:(UIButton *)sender{
//叠加视图
OtherViewController * other=[[OtherViewController alloc]init];
[self presentViewController:other animated:YES completion:nil];
}
//viewDidApper视图已经显示
//viewWillDissappear视图已经消失
//viewDidDissappear视图已经消失
//内存报警 didReceiveMemoryWarning
//otherViewController.h
UIViewController界面切换,UIViewController界面传值:
//AppDelegate.m
#import "RootViewController.h"
self.window.backgroundColor=[UIColor blueColor];//证明视图控制器的颜色是透明的
RootViewController * root=[[RootViewController alloc]init];
slef.window.rootViewController=root;
[self.window makeKeyAndVisible];
//RootViewController 继承UIViewController
#import "OtherViewController.h"
@interface RootViewController:UIViewController<passValue>
{
UITextField * text;
}
//---
#import "OtherViewController.h"
-(void)setString:(NSString * str){
text.text=str;
}
-(void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundcolor=[UIColor greenColor];
text=[[UITextField alloc]initWithFrame:CGRectMake(0,20,200,50)];
[self.view addSubview:text];
UIButton * btn=[[UIButton alloc]initWithFrame:CGRectMake(0,70,200,50)];
btn.backgroundcolor=[UIColor blackColor];
[btn setTitle:@"显示另外一个视图" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(showTap:)forControlEvents:UIControlEventTouchInSide];
[self.view addSubview:btn];
}
-(void)showTap:(id)sender{
//采用另外一种切换方式,模态切换:关闭当前视图下一个视图无法操作
//呈现
//设置转场动态
OtherViewController * other=[[OtherViewController alloc]init];
[other setModealTransitionStyleConverVertical];//从下面拉入 CrossDissolve溶解
//FlipHorizontal 水平翻转 PattialCurl翻页翻转
other.passString=text.text;
other.delegate=self;//本身实现这个代理
[self presentViewController:other animated:YES completion:nil];
}
//OtherViewController.h
@protocol passValue
-(void)setString:(NSString *)str;
@end
@interface
{
UITextField * text;
}
@property(strong,nonatomic)NSStirng * passString;
@property(stirng,nonatomic)id<passValue>delegate;//这里的对象必须实现括号的协议
//---
-(void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundcolor=[UIColor redColor];
text.text=self.pasString;//能传,不能回
text=[[UITextFiedl allco]initWithFrame:CGRectMake(100,100,200,50)];
//关闭当前视图
UIButton * btn=[[UIButton alloc]initWithFrameL:CGRectMake(100,170,200,50)];
[btn setTitle:@"关闭" forState:UIControlSstateNorMal];
btn.backgroundcolor=[UIColor redColor];
[btn addTarget:self action:@selector(closeTap:)forControlEvents:UIControlEventTouchInSide];
//视图值传递,视图方式,代理方式
}
-(void)closTap:(id)sender
{
【self.delegate setString:text.text]
[self.dismissViewCOntrollerAnimated:YES complertion:nil];
}
UINavigationController
导航:UINavigationController视图切换与定制
#import "RootViewController.h"
RootViewCOntroller * root=[[RootViewController aloc]init];//创建普通视图控制器
//创建一个导航视图控制器,把普通视图控制器作为它的根视图控制器
[[UINavigateionBar apperaance] setBarTintColor:[UIColor yellowColor]];
UINavigationController * nav=[[UINavigationController alloc]initWithRootViewController:root];
self.window.rootViewController=nav;
[self.window makeKeyAndVisible];
//RootViewController.h
#import "OtherViewController.h"
-(instancetype)initWithNiName:(NSString *)nibNameOrNil bundle:(NSBundle *)niBundleOrNil{
self=[supr initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if(self){
self.title=@"主视图";
}
return self;
}
-(void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor=[UIColor redColor];
//导航条64
UIButton * btn=[[UIButton alloc]initWithFrame:CGRectMake(0,64,320,50)];
btn.backgroundColor=[UIColor blackColor];
[btn setTtile:@"显示另一个视图" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(showTap:) forControlEvents:UIControlEventTouchUpInSide];
[self.veiw addSubview:btn];
}
-(void)showTap:(id)sender{
OtherViewControllerr * other=[[OhterViewController alloc]init];
// [self presentViewController:other animated:YES completion:nill]; 模态方式 覆盖
//进栈方式 导航视图不宜使用模态
[self.navigationController pushViewController:other animated:YES];
}
//OtherViewController.h
-(instancetype)initWithNiName:(NSString *)nibNameOrNil bundle:(NSBundle *)niBundleOrNil{
self=[supr initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if(self){
self.title=@"另一个视图";
UIBarButtonItem * bi=[[UIBarButtonItem alloc]initWithTtile:@"返回" style:UIBarButtonItemStylePlain targer:slef action:@selector(closeTap)];
self.navigationItem.leftBarButtonItem=bi;
UIBarButtonItem * bi2=[[UIBarButtonItem alloc]initWithTtile:@"完成" style:UIBarButtonItemStylePlain targer:slef action:@selector(closeTap)];
self.navigationItem.rightBarButtonItem=bi2;
UISegmentedControl * seg=[[UISegmentedControl alloc]initWithItems:[NSArray arrayWithObjects:@"我",@"你",nil]];
seg.selectedSegmentIndex=0;
self.navigationItem.titleView=seg;
}
return self;
}
-(void)vieDidLoad{
[super viewDidLoad];
UIButton * btn=[[UIButton alloc]initWithFrame:CGRectMake(0,64,320,40)];
btn.backgroundColor=[UIColor blackColor];
[btn setTtile:@"关闭" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(closeTap:) forControlEvents:UIControlEventTouchUpInSide];
[self.veiw addSubview:btn];
self.view.backgroundColor=[UIColor greenColor];
}
-(void)closeTap:(id)sender{
[self.navigationController popViewCOntrollerAnimated:YES];
}
UITabbarController
标签栏视图
//AppDelegate.m
#import "ViewController1.h"
#import "ViewController2.h"
#import "ViewController3.h"
UITabBarController * tc=[[UITabBarController alloc]init];
ViewController1 * v1=[[ViewController1 alloc]init];
ViewController2 * v2=[[ViewController2 alloc]init];
ViewController3 * v3=[[ViewController3 alloc]init];
UINavigationController * nav1=[[UINavigationController alloc]initWithRootViewController:v1];
UINavigationController * nav2=[[UINavigationController alloc]initWithRootViewController:v2];
UINavigationController * nav3=[[UINavigationController alloc]initWithRootViewController:v3];
[tc setViewControllers:[NSArray arrayWithObjects:nav1,nav2,nav3,nil]];
self.window.rootViewCOntroller=tc;
[self.window makeKeyAndVisible];
//ViewController1.h
-(instancetype)initWithNiName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
self=[super initWithNibName:nibNameOrNil bundle: niBundleOrNil];
if(self){
self.title=@"one";
self.tabBarItem.title=@"one";
self.tabBarItem.image=[UIImgae imageNamed:@"first.png"];
}
return self;
}
-(void)viwDidLoad{
[super viewDidLoad];
UIButton * btn=[[UIButton alloc]initWithFrame:CGRectMake(0,20,350,50)];
btn.backgroundColor=[UIColor greenColor];
[btn setTtile:@"one" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(closeTap:) forControlEvents:UIControlEventTouchUpInSide];
[self.veiw addSubview:btn];
}
//ViewController2.h
-(instancetype)initWithNiName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
self=[super initWithNibName:nibNameOrNil bundle: niBundleOrNil];
if(self){
self.title=@"two";
self.tabBarItem.title=@"two";
self.tabBarItem.image=[UIImgae imageNamed:@"second.png"];
}
return self;
}
-(void)viwDidLoad{
UIButton * btn=[[UIButton alloc]initWithFrame:CGRectMake(0,20,350,50)];
btn.backgroundColor=[UIColor redColor];
[btn setTtile:@"two" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(closeTap:) forControlEvents:UIControlEventTouchUpInSide];
[self.veiw addSubview:btn];
}
//ViewController3.h 正常是呈现5标签,多了以列表形式于最后一个
-(instancetype)initWithNiName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
self=[super initWithNibName:nibNameOrNil bundle: niBundleOrNil];
if(self){
self.title=@"three";
self.tabBarItem.title=@"three";
}
return self;
}
-(void)viwDidLoad{
UIButton * btn=[[UIButton alloc]initWithFrame:CGRectMake(0,20,350,50)];
btn.backgroundColor=[UIColor redColor];
[btn setTtile:@"two" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(closeTap:) forControlEvents:UIControlEventTouchUpInSide];
[self.veiw addSubview:btn];
}
UIScrollView
滚动视图+页控件UIPageControl
//Appdelegate.h
@interface AppDelegate:UIResponder<UIApplicationDelegate,UIScrollViewDelegate>
{
UIPageControl * pc;
UIScrollView * sv;
}
//Appdelegate.m
sv=[[UIScrollView alloc]initWithFrame:CGRectMake(60,60,200,200)];
sv.backgroundColor=[UIColor grayColor];
UIView * v1=[[UIView alloc]initWithFrame:CGRectMake(5,5,190,190)];
v1.backgroundColor=[UIColor redColor];
[sv addSubview:v1];
UIView * v2=[[UIView alloc]initWithFrame:CGRectMake(205,5,190,190)];
v2.backgroundColor=[UIColor greenColor];
[sv addSubview:v2];
UIView * v3=[[UIView alloc]initWithFrame:CGRectMake(405,5,190,190)];
v3.backgroundColor=[UIColor blueColor];
[sv addSubview:v3];
sv.pagingEnabled=YES;//允许滚动
sv.contentSize=CGSizeMake(600,200);//滚动范围
sv.contentOffSet=CGPointMake(200,0);//指定偏移坐标
//代理
sv.delegate=self;//滚动视图事件由self代理
pc=[[UIPageControl alloc]initWithFrame:CGRectMake(135,200,50,37)];
pc.numberOfPages=3;
pc.pageIndicatorTintColor=[UIColor blackColor];
pc.currentPage=1;
//page没有代理,用目标实现
[pc addTarget:self action:@selector(valueChange:)forControlEvents:UIControlEventValueChanged];
[self.window addSubview:pc];
[self.window addSubview:sv];
[self.window makeKeyAndVisible];
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
float width=scrollView.frame.size.width;
int n=(scrollView.contrentOffset.x-width/2)width+1;//一个算法
pc.currentPage=n;
}
-(void)valueChange:(UIPageControl *)page{//page可控制滚动视图
sv.contentOffset=CGPointMake(200*page.currentPage,0);
}
UITableView
表视图
//Appdelegate.m
#import "MainViewController.h"
#import "MainTableViewController.h"
//MainViewController * main[[MainViewController alloc]init];
MainTableViewCOntroller * tvc=[[MainTableViewController alloc]init];
UINavigationController * nav=[[UINavigationController alloc]initWihtRootViewController:tvc];
//self.window.rootViewController=main;
self.window.rootViewController=nav;
[self.window makeKeyAndVisible];
@interface MainViewController:UIViewCOntrollr<UITableViewDataSource,UITabelViewDelegate>
@property(strong,nonatomic)UITableView * tabelView;
@property(strong,nonatomic)NSMutableArray * names;
//MainViewController.m
-(void)DidLoad{
[super DidLoad];
self.names=[NSMutabelArray arrayWithObjects:@"a",@"b",@"c",@"d",nil];
self.view.backgroundColor=[UIColor greenColor];
self.tableView=[[UITabelView alloc]initWithFrame:CGRectMake(0,0,320,480) style:UItableViewStylePlain];
self.tableView.dataSource=self;//指定数据源,指向一个对象,self需要实现一个协议
self.tableView.delegate=self;
[self.view addSubviw:self.tableView];
}
//确定有多少个区
-(NSInteger)numberOFSectionsInTableView:(UITableView *)tableView{
return 1;
}
//确定区中有多少行
-(NSInteger)tableView:(UITableView *)tableVIew numberOfRowsInSection:(NSInterger)section{
return self.names.count;
}
//告诉表试图单元的具体情况
-(UITableViewCell *)tableView:(UITableViw *)tableView cellForRowAtIndexPath:(NSIndexpath *)indexPath{
//先从内存中去获取一个单元
UITabelViewCell *cell=[tableView dequeueReusabelCellWithIndetifier:@"mycell"];
if(cell==nil){//如果没有这个单元,创建一个单元
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIndetifier:@"mycell"];
}
//让这个单元里的标签显示文本为集合中对应的文本
cell.textLabel.text=self.names[indexPath.row];
return cell;
}
//以上是单独创建一个表视图放在一个视图上
//ios中有标示图控制器
//MainTabelViewController.m 继承UITableViewController
@interface
{
@property (strong,nonatomic)NSMutableArray * names;
@property (strong,nonatomic)MSMutableArray * sexs;
}
//---
-(instancetype)initWithStyle:(UITableViewStyle)style{
self=[super initWithSthle:style];
if(self){
self.title=@"主菜单";
}
return self;
}
-(void)viewDidLoad{
[super viewDidLoad];
self.names=[NSMutabelArray arrayWithObjects:@"a",@"b",@"c",@"d",nil];
self.sexs=[NSMutabelArray arrayWithObjects:@"男歌星",@"女歌星",@"男歌星",@"女演员",nil];
}
//呈现数据必须要有3个方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInterger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInterger)section{
return self.names.count;
}
//表格的单元里面默认有四个控件:从左到右:图片控件UIIamgeView 文本标签textlable,详细文本标签detailTextLabel,附件accessoryType
-(UITabelViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString * cellid=@"mycell";
UITableViewCell * cell=[tableView dequeueReusableClllWithIdentifier: cellid ];
if(cell==nil){
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIndetifier:@"mycell"];//UITableViewCellStyleDefault 单元样式
//UITableViewCellStyleValue1 值1样式
//UITableViewCellStyleValue2 值2样式
}
cell.textLabel.text=self.names[indexPath.row];
cell.textLabel.textColor=[UIColor redColor];
cell.textLabel.font=[UIFont boldsysytemFontOfSize:36];
cell.imgaeView.image=[UIImage imageNamed:@"a.png"];
//cell.detailTextLabel.text=@"男歌星";
cell.detailTextLabel.text=self.sexs[indexPaht.row];
//单元附件的样式
//UITableViewCellAccessoryCheckMark 选中
//UITableViewCellAccessoryDetailButton 详细按钮
//UITableViewCellAccessoryDetailDisclosureButton 详细展示按钮
//UITableViewCellAccessoryDisCLousureIndicator 展示表示
cell.accessoryType=UITableViewCellAccessoryCheckMark;
return cell;
}
//单元缩进
-(NSInteger)tableViw:(UITableView *)tableView indentationLevelFroRowAtIndexPath:(NSIndexPath *)indexPath{
return indexPath.row;//逐行缩进
}
//单元格的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 60;
}
//选中某一行
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSLog(@"%d",indexpath.row);
}
定制单元格
//Appdelegate.m
#import "MainViewController.h"
#import "MainTableViewController.h"
MainTableViewCOntroller * main=[[MainTableViewController alloc]initWithStyle:UITableViewStyleGrouped];//分组样式
UINavigationController * nav=[[UINavigationController alloc]initWihtRootViewController:main];
self.window.rootViewController=nav;
[self.window makeKeyAndVisible];
//以上是单独创建一个表视图放在一个视图上
//ios中有标示图控制器
//MainTabelViewController.m 继承UITableViewController
#import "MyTableViewCell.h"
@interface
@property (strong,nonatomic)NSMutableArray * names;
//---
-(instancetype)initWithStyle:(UITableViewStyle)style{
self=[super initWithSthle:style];
if(self){
self.title=@"";
}
return self;
}
-(void)viewDidLoad{
[super viewDidLoad];
self.names=[NSMutabelArray arrayWithObjects:@"百度",@"新浪",@"腾讯",@"谷歌",nil];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
//return 1;
return 2;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
return @"分区头";
}
-(NSInterger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInterger)section{
return self.names.count;
}
-(UITabelViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString * cellid=@"mycell";
// UITableViewCell * cell=[atbleView dequeueReusableClllWithIdentifier: cellid ];
MyTableViewCell * cell=[tableView dequeueReusableClllWithIdentifier: cellid ];
if(cell==nil){
cell=[[MyTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIndetifier:@"mycell"];
}
// cell.textLabel.text=self.names[indexPath.row];
cell.webname.text=self.names[indexpath.row];
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 60;
}
//删除数据
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPaht{
//内存删除
[self.names removeObjectAtIndex:indexPath.row] ;
//界面删除
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]withRowAnimation:UITableViewRowAnimationAutomatic];
}
@interface
@property(strong,nonatomic) UITextField * webname;
//MyTableVeiwCell.m 继承UITableViewCell
-(instancetype)initWithStyle:(UITableViewCeellStyle)style reuseIdentifier:(NSString *) reuseIdentifier{
self=[super initWithStyle:style reuseIdentifier:reuseIdentifier];
if(self){
self.webname=[[UITextField allod]initWithFrame:CGRectMake(0,10,1150,40)];
text.backgroundColor=[UIColor yellowColor];
//text.text=@"xxxx";
[self addSubview:text];
UIButton * btn=[[UIButton alloc]initWithFrame:CGRectMake(180,10,130,40)];
btn.backgroundColor=[UIColor yellorColor];
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[btn setTitle:@"确定" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(okTap)forControlEvents:UIControlEventTouchUpInside ];
[self addSubview:btn];
}
return self;
}
-(void)okTap{
UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" messgae:self.webname.text delegate:self cancelButtonTitle:@"知道" otherBUttonTiles:nil,nil];
[alert show];
}
-(void)awakeFromNib{
}
如何分区显示数据,索引数据,下拉刷新
//Appdelegate.m
#import "MainViewController.h"
#import "MainTableViewController.h"
MainTableViewCOntroller * main=[[MainTableViewController alloc]initWithStyle:UITableViewStyleGrouped];
UINavigationController * nav=[[UINavigationController alloc]initWihtRootViewController:main];
self.window.rootViewController=nav;
//创造字符串
NSMutableDictionary * dic=[NSMutableDictionary dictionaryWithCapacity:1000];
for(int i=0;i<1000;i++){
//a=97 大写 -32
int n1=arc4random()%26+97;
int n2=arc4random()%26+97;
int n3=arc4random()%26+97;
int n4=arc4random()%26+97;
int n5=arc4random()%26+97;
NSString * str=[NSString stringWithFormat:@"%c%c%c%c%c",n1,n2,n3,n4,n5];
NSString * str2=[NSString stringWithFormat:@"%c",n1-32];
NSArray * arr=[dict objectForKey:str2];
NSMutableArray * arr2;
if(arr==nil){
arr=[NSArray arrayWithObject:str];
arr2=[NSMutableArray arrayWithArray:arr];
}
else{
arr2=[NSMutableArray arrayWithArray:arr];//复制过来
[arr2 addObject:str1];//再添加
}
[dict setObject:arr2 forKey:str2];
}
[dict writeToFile:@"data.plist" atomically:YES];
[self.window makeKeyAndVisible];
//MainTabelViewController.m 继承UITableViewController
@interface
@property (strong,nonatomic)NSMutableArray * keys;
@property (strong,nonatomic)NSDictionary * data;
//---
-(void)viewDidLoad{
[super viewDidLoad];
NSString * path=[[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"];
self.keys=[[self.data allKeys]sortedArrayUsingSelector:@selector(compare:)];
self.data=[NSDictionary dictionaryWithContentsOfFile:path];
//下拉刷新
self.refreshCOntrol=[[UIRefreshControl alloc]init];
//监听行为
[self.refreshControl addTarget:self action:@secletor(refresh) forControlEvents:UIControlEentValueChanged];
[self.refreshControl.attributedTitle=[NSAttributesdString alloc]initWithString:@"正在刷新..."];
}
-(void)refresh{
//远程获取数据
//结束刷新
[self.refreshControl.attributedTitle=[NSAttributesdString alloc]initWithString:@"刷新成功..."];
[self.refreshControl endRefreshing];
//表格重新加载
[self.tableView reloadData];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
NSString * strKey=[self.keys objectAtIndex:section];//获取分区的字符串
NSArray * arr=[self.data objecctForKey:strKey];//获取键的值
return arr.count;
}
-(NSInterger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInterger)section{
return self.keys.count;
}
-(UITabelViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString * cellid=@"mycell";
UITableViewCell * cell=[tableView dequeueReusableClllWithIdentifier: cellid ];
if(cell==nil){
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIndetifier:@"mycell"];
}
//cell.textLabel.text=self.keys[indexpath.row];
NSString * strKey=[self.keys objectAtIndex:indexPath.section]
NSArray * arr=[[self.data objecctForKey:strKey]sortedArrayUsingSelector:@selector(compare:)];//排序
cell.textLabel.text=arr[indexPath.row];
return cell;
}
//添加索引
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
return self.keys[section];
}
-(NSArray *)sectionIndexTitlesForTabelView:(UITableView *)tableView{
return self.keys;
}
搜索文章来源:https://www.toymoban.com/news/detail-424447.html
//Appdelegate.m
#import "MainViewController.h"
#import "MainTableViewController.h"
MainTableViewCOntroller * main=[[MainTableViewController alloc]initWithStyle:UITableViewStylePlain];
UINavigationController * nav=[[UINavigationController alloc]initWihtRootViewController:main];
self.window.rootViewController=nav;
[self.window makeKeyAndVisible];
//MainTabelViewController.m 继承UITableViewController
@interface MainTabelViewController:UITabelViewController<UISearchBarDelegate>
@property (strong,nonatomic)NSMutableArray * strings;
@property (strong,nonatomic)NSArray * shows;
//---
-(void)viewDidLoad{
[super viewDidLoad];
self.strings=[[NSMutableArray alloc]initWithCapaticty:1000];
for(int i=0;i<1000;i++){
//a=97 大写 -32
int n1=arc4random()%26+97;
int n2=arc4random()%26+97;
int n3=arc4random()%26+97;
int n4=arc4random()%26+97;
int n5=arc4random()%26+97;
NSString * str=[NSString stringWithFormat:@"%c%c%c%c%c",n1,n2,n3,n4,n5];
[self.strings addObject:str];
}
slef.shows=[self.strings copy];
UISearchBar * sb=[[UISearchBar alloc]initWithFrame:CGRectMake(0,0,320,40)];
sb.autocorrectionType=UITextAutocorrectionTypeNo; //自动拼写检查
sb.autocapitalizationType=UITextAutocapiatlizationTypeNone;//取消首字母大小
sb.showCancelButton=NO;//显示取消按钮
sb.placeholder=@"输入查找信息";
sb.delegate=self;
self.tabelView.tableHeaderView=sb;//放在表头上
}
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
searchBar.showsCancelButton=YES;
}
-(void)searchBarCancelButtonCLicked:(UISearchBar *)searchBar{
self.shows=[self.strings copy];
searchBar.showsCancelButton=NO;
[self.tableView reloadData];//显示原始数据
//收起键盘
[searchBar resignFirstResponder];//搜索栏失去焦点
}
-(void)searchBarSearchButtonCLicked:(UISearchBar *)searchBar{
NSMutableArray * array=[[NSMutableArrya alloc]initWithCapactity:1000];
for(NSString * str in self.strings){
if([str.ranOfString:searchBar.text].location!=NSNotFound){
[array addObject:str];
}
}
self.shows=[array copy];
[self.tableView reloadData];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInterger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInterger)section{
return self.shows.count;
}
-(UITabelViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString * cellid=@"mycell";
UITableViewCell * cell=[tableView dequeueReusableClllWithIdentifier: cellid ];
if(cell==nil){
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIndetifier:@"mycell"];
}
cell.textLabel.text=self.shows[indexPath.row];
return cell;
}
UITableViewCell之不同高度的动态单元格文章来源地址https://www.toymoban.com/news/detail-424447.html
//Appdelegate.m
#import "MainViewController.h"
[self.window makeKeyAndVisible];
//ViewController.m
//要想要表格显示数据,要实现两个协议,分别是显示数据和处理事件
#import "TabelViewCell1.h"
#import "TabelViewCell2.h"
@interface ViewController:UITabelViewController<UITabelViewDataSource,UITableViewDelegate>
@property (strong,nonatomic)NSMutableArray * strings;
//---
-(void)viewDidLoad{
[super viewDidLoad];
UITableView * tableView=[[UITableView alloc]initWithFrame:CGrectMake(0,20,self.view.frame.size.width,self.view.frame.height)];
tableView.dataSource=self;
tableView.delegate=self;
[self.view addSubview:tableview];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInterger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInterger)section{
return 10;
}
-(UITabelViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
/*
static NSString * cellid=@"mycell";
TabelViewCell1 * cell=[tableView dequeueReusableClllWithIdentifier: cellid ];
if(cell==nil){
cell=[[TabelViewCell1 alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIndetifier:@"mycell"];
}
// cell.textLabel.text=@"2222";
*/
UITableViewCell * cell;
if(indPath.row%2==0){
cell=[tableView dequeueReusableClllWithIdentifier: @"cell1" ];
if(cell==nil){
cell=[[TabelViewCell1 alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIndetifier:@"cell1"];
}
}else{
cell=[tableView dequeueReusableClllWithIdentifier: @"cell2" ];
if(cell==nil){
cell=[[TabelViewCell2 alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIndetifier:@"cell2"];
}
}
return cell;
}
-(NSInteger)tableView;(UItableView* )tableView heightForRowAtIndexPath:(NsIndexPath *)indexPath{//调节高度
if(indPath.row%2==0){
return 80;
}else{
return 180;
}
}
//表单元子类
//TableViewCell1.m
-(instancetype)initWithStye:(UITableViewCCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
self=[self initWithStye:style reuseIdentifier:reuseIdentifier];
if(self){
UITextView * tv=[[UITextView alloc]initWithFrame:CGRectMake(0,0,200,80)];
tv.backgroundCOlor=[UIColor lightGrayColor];
[self addsubview:tv];
}
return self;
}
//表单元子类
//TableViewCell2.m
-(instancetype)initWithStye:(UITableViewCCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
self=[self initWithStye:style reuseIdentifier:reuseIdentifier];
if(self){
UIView * tv=[[UIView alloc]initWithFrame:CGRectMake(0,0,200,180)];
tv.backgroundCOlor=[UIColor redColor];
[self addsubview:tv];
}
return self;
}
到了这里,关于iOS学习01的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!