iOS中如何使横向展示的文字纵向居中

之前面试过几个人,一个很小的问题却回答的不是很好。自己项目里也出现过这样的问题。居中确实是工作了两三年后才知道怎么实现的。

 

UILabel

    //
    //父视图 高度会跟着屏幕变
    //
    UIView *superView_ = [[UIView alloc]initWithFrame:CGRectMake(0, 100, 320, [UIScreen mainScreen].bounds.size.height * 0.2 )];
    superView_.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:superView_];
    //
    //需要居中的UILabel
    //
    
    /*
    UILabel *label_ = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 10)];
    label_.text = @"扣款成功克服超市老板VR发";
    [superView_ addSubview:label_];
    */

 

    //两个问题:1事先写好坐标后 文字可能展示不全   2居中也会有问题

 

    //
    //合理的代码 只看纵向居中
    //
    
    /*
    UILabel *label_ = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    label_.text = @"扣款成功克服超市老板VR发";
    [label_ sizeToFit];
    CGPoint center = CGPointMake(label_.center.x, superView_.frame.size.height / 2.0);
    label_.center = center;
    [superView_ addSubview:label_];
    */

    //一个问题:center我们只改y可是它是结构体 能不能节省代码  可以为UIView添加一个centerY的方法

//
//  UIView+YYY.h
//  CenterDemo
//
//  Created by YYY on 2019/1/8.
//  Copyright © 2019 YYY. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface UIView (YYY)

@property (nonatomic,assign) CGFloat centerY;

- (CGFloat)centerY;
- (void)setCenterY:(CGFloat)ty;
@end
//
//  UIView+YYY.m
//  CenterDemo
//
//  Created by YYY on 2019/1/8.
//  Copyright © 2019 YYY. All rights reserved.
//

#import "UIView+YYY.h"

@implementation UIView (YYY)
- (CGFloat)centerY{
    return self.center.y;
}
- (void)setCenterY:(CGFloat)ty{
    CGPoint center = self.center;
    center.y = ty;
    self.center = center;
}
@end

    //

    //优化后的代码

    //

    UILabel *label_ = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    label_.text = @"扣款成功克服超市老板VR发";
    [label_ sizeToFit];
    label_.centerY = superView_.frame.size.height / 2.0;
    [superView_ addSubview:label_];

 

代码下载地址      https://github.com/XiaoHeHe1/CenterDemo

 

textfiled 第一响应的时候里面的holder可能会上下动   这时修改一下输入框的高度即可解决

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值