UIButton图片位置设置

作者: xingou | 来源:发表于2016-02-03 10:13 被阅读1757次

    作为一名已经100天的ios小菜, 我也决定开始学习写点东西了。刚刚需要设置UIbuttom的图片位置,stackoverflow了一番,找到了这个:ios - iPhone UIButton - image position - Stack Overflow

    里面投票最高的是

    button.titleEdgeInsets = UIEdgeInsetsMake(0, -button.imageView.frame.size.width, 0, button.imageView.frame.size.width);

    button.imageEdgeInsets = UIEdgeInsetsMake(0, button.titleLabel.frame.size.width, 0, -button.titleLabel.frame.size.width);

    我更希望能直接在storyboard中直接设置图片上下左右的位置,于是乎来吧,扩展UIButton, 利用kvc 直接设置:

    ```

    extension UIButton {

    func setImageUp(state:Bool){

         if(self.imageView == nil || self.titleLabel == nil || state == false){ return }

            self.sizeToFit()

            let titleXOffset = self.imageView!.frame.width/2

            let titleYOffset = self.imageView!.frame.height/2

            self.titleEdgeInsets = UIEdgeInsetsMake(titleYOffset, -titleXOffset, -titleYOffset, titleXOffset)

            let imageXoffset = self.titleLabel!.frame.width/2

            let imageYoffset = self.titleLabel!.frame.height/2

            self.imageEdgeInsets = UIEdgeInsetsMake(-imageYoffset, imageXoffset, imageYoffset, -imageXoffset)

    }

    func setImageBottom(state:Bool){

        if(self.imageView == nil || self.titleLabel == nil || state == false){ return }

           self.sizeToFit()

            let titleXOffset = self.imageView!.frame.width/2

            let titleYOffset = self.imageView!.frame.height/2

            self.titleEdgeInsets = UIEdgeInsetsMake(-titleYOffset, -titleXOffset, titleYOffset, titleXOffset)

            let imageXoffset = self.titleLabel!.frame.width/2

            let imageYoffset = self.titleLabel!.frame.height/2

            self.imageEdgeInsets = UIEdgeInsetsMake(imageYoffset, imageXoffset, -imageYoffset, -imageXoffset)

    }

    func setImageRight(state:Bool){

        if(self.imageView == nil || self.titleLabel == nil || state == false){ return }

        self.sizeToFit()

        self.titleEdgeInsets = UIEdgeInsetsMake(0, -self.imageView!.frame.size.width, 0, self.imageView!.frame.size.width)

        self.imageEdgeInsets = UIEdgeInsetsMake(0, self.titleLabel!.frame.size.width, 0, -self.titleLabel!.frame.size.width)

    }

    }

    ok,现在直接在storyboard中的user defined runtime attributes中设置就行了

    结果

    有不对的地方,欢迎大神指正。。。

    相关文章

      网友评论

        本文标题:UIButton图片位置设置

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