zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

ios成长之每日一遍(day 2)

ios 每日 成长 Day 一遍
2023-09-27 14:27:23 时间

接着下来简单说说Label(相当于android的textview)和button的使用, 由于都是与上篇的AppDelegate一致, 所以这一篇就说说ViewController与xib的使用呗。

BIDViewController.h

#import <UIKit/UIKit.h>

@interface BIDViewController : UIViewController    // 类的开始

@property (weak, nonatomic) IBOutlet UILabel *statusLabel;    
// a. @property是定义属性的关键字; b. weak与strong关键字的区别, strong表示对象没有被释放则一直持有对象, 而weak指向的地址一旦被释放,这些指针都将被赋值为nil c. atomic、nonatomic、assign、copy、retain关键字的区别, atomic是默认的设置,提供多线程安全, 但是会影响效率; nonatomic线程不安全, 提高性能; assign用于基本的数据类型; retain用于NSObject和其子类; copy复制对象到新的地址; ps:copy 其实是建立了一个相同的对象,而 retain 不是:比如一个NSString 对象,地址为 0×1111,内容为 @”STR” , copy 到另外一个 NSString 之后,地址为 0×2222 ,内容相同,新的对象 retain 为 1 ,旧有对象没有变化; retain 到另外一个 NSString 之后,地址相同(建立一个指针,指针拷贝),内容当然相同,这个对象的 retain 值 +1。也就是说, retain 是指针拷贝, copy 是内容拷贝。
IBOutlet只是一个标记, 用于表示已在xib定义实现, xib连接时按住ctrl键, 鼠标从File's Owner拖动到在代码中标有IBOutlet的空间上, 然后在弹出框选择

- (IBAction)buttonPressed:(UIButton *)sender;    // 定义操作触发的函数, IBAction也是一个标识, 标记这是触发函数, xib中在需要触发函数的控键上按住ctrl键, 鼠标从该控键拖动到File's Owner并选择相应的函数即可

@end    // 类的结束

 

 BIDViewController.m

#import "BIDViewController.h"

@implementation BIDViewController
@synthesize statusLabel;    // 与property一般成对出现

- (IBAction)buttonPressed:(UIButton *)sender {
    NSString *title = [sender titleForState:UIControlStateNormal];   // 返回控键指定状态的title 
    NSString *plainText = [NSString stringWithFormat:@"%@ button pressed.", title];    // %@表示这个参数时对象类型

    /***  让部分文字变色方法  **/
    NSMutableAttributedString *styledText = [[NSMutableAttributedString alloc]
                                             initWithString:plainText];
    // 这语法有点儿像json哇
    NSDictionary *attributes = @{
    NSFontAttributeName : [UIFont boldSystemFontOfSize:statusLabel.font.pointSize]
    };

    NSRange nameRange = [plainText rangeOfString:title];
    
    [styledText setAttributes:attributes
                        range:nameRange];
    statusLabel.attributedText = styledText;
}
@end


第二篇结束!!!