美文网首页iOS初学之OC
关于layoutSubviews方法何时使用的总结

关于layoutSubviews方法何时使用的总结

作者: CharlesAn | 来源:发表于2017-05-26 11:17 被阅读79次

    今天在自定义button时,遇到了关于layoutSubviews方法调用的问题,由于使用的是sizeTofit自适应的方法,所以初始化时并没有给按钮设置frame,,只是在layout方法里改变了titleLable和imageView的位置,按钮却能正常显示,就想到什么时候走了layout方法。

    - (void)layoutSubviews{
        
       [super layoutSubviews];
        NSLog(@"layout1");
        self.backgroundColor = [UIColor redColor];
       self.titleLabel.frame =    CGRectMake(self.imageView.frame.origin.x, self.titleLabel.frame.origin.y, self.titleLabel.frame.size.width, self.titleLabel.frame.size.height);
       
        self.imageView.frame = CGRectMake(CGRectGetMaxX(self.titleLabel.frame), self.imageView.frame.origin.y, self.imageView.frame.size.width, self.imageView.frame.size.height);
    }
    - (void)setTitle:(NSString *)title forState:(UIControlState)state{
        
        [super setTitle:title forState:state];
        NSLog(@"settitle");
        [self sizeToFit];
    }
    
    - (void)setImage:(UIImage *)image forState:(UIControlState)state{
        NSLog(@"setimage");
        [super setImage:image forState:state];
        [self sizeToFit];
    }
    
    
    • 何时使用layout
    1.init方法不会触发
    2.改变frame大小时会触发layoutSubviews方法
    3.addSubview会触发layoutSubviews

    相关文章

      网友评论

        本文标题:关于layoutSubviews方法何时使用的总结

        本文链接:https://www.haomeiwen.com/subject/qbgtfxtx.html