UILabel的使用、事件响应及传值

创建圆角label,类似输入框的效果,可以这样使用:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
label.backgroundColor = [UIColor blueColor];
// 设置圆角
label.layer.cornerRadius = 10;
[self.view addSubview:label];

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 36)];
label.layer.borderWidth  = 1.0f;
label.layer.borderColor  = [UIColor darkGrayColor].CGColor;
label.layer.cornerRadius = 5.0f;

UILabel事件响应:

添加一个UILabel,并为label添加了点击事件,怎么才能让事件响应?

UITapGestureRecognizer *tapGestureTel = [[[UITapGestureRecognizeralloc]initWithTarget:self action:@selector(onLabelEvent:)]autorelease];
    [myLabel addGestureRecognizer:tapGestureTel];

-(void) onLabelEvent:(UITapGestureRecognizer *)recognizer{
   UILabel *label=(UILabel*)recognizer.view;
   NSLog(@"%@被点击了",label.text);

}

UILabel 也是一个UIView,同样继承自UIResponder,所以只要扩展UILabel,并覆盖相关方法就可以了,如:

– touchesBegan:withEvent:  
– touchesMoved:withEvent:  
– touchesEnded:withEvent:  
– touchesCancelled:withEvent:   

如:

// 点击该label的时候, 来个高亮显示
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self setTextColor:[UIColor whiteColor]];
}



// 还原label颜色,获取手指离开屏幕时的坐标点, 在label范围内的话就可以触发自定义的操作
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [self setTextColor:COLOR(59,136,195,1.0)];
    UITouch *touch = [touches anyObject];
    CGPoint points = [touch locationInView:self];
    if (points.x >= self.frame.origin.x && points.y >= self.frame.origin.x && points.x <= self.frame.size.width && points.y <= self.frame.size.height)
    {
        [delegate myLabel:self touchesWtihTag:self.tag];
    }
}



换个思路,既然要加点击事件,为什么不用UIButton,而用UILabel呢?

原因主要是有时通过UIButton无法实现对文字的完美控制,笔者在项目中就遇到这样的情形:当使用粗斜体+大号字体显示文本时,会有部分文字显示不全。


UILabel添加背景图片

UIColor *color = [UIColor colorWithPatternImage:[UIImage imageNamed:@"itemkaung2.png"]];
[myLabel setBackgroundColor:color];

UILabel如何设置文字居中

label.textAlignment = UITextAlignmentLeft;
label.textAlignment = UITextAlignmentCenter;
label.textAlignment = UITextAlignmentRight;




你可能感兴趣的:(iOS)