HarmonyOS Slider滑动自定义tips?

Slider滑动上方显示的tips能否自定义样式,实现如下图效果,如果不行有什么替代方案吗

阅读 673
1 个回答
@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  @State c:number=40
  build() {
    Column() {
      Text(this.c.toString()+"℃")
      Row(){
        Text('35')
        Slider({value:40,min:35,max:50,style:SliderStyle.OutSet})
          .width('60%')
          .trackColor(Color.Orange)
          .selectedColor(Color.Orange)
          .onChange((val:number)=>{
            this.c=val
          })
        Text('50')
      }
    }
    .height('100%')
    .width('100%')
  }
}

tip想自定义样式静态的话可以参考如下代码:

const BLOCK_DEFAULT_BORDER_WIDTH = 4;

@Entry
@Component
struct SliderIndex {
  @State isTipShow: boolean = false;
  @State tipsOffset: number = 0;
  private slideHeight: number = 300;
  private blockSize: number = 20;
  private tipHeight: number = 40;
  private hideTipTask?: number;

  private showTip(value: number) {
    this.isTipShow = true
    let percent = Number((value / 100).toFixed(2));
    this.tipsOffset = (this.slideHeight - this.blockSize - BLOCK_DEFAULT_BORDER_WIDTH * 2) * percent
      - (this.tipHeight / 2 - (this.blockSize / 2 + BLOCK_DEFAULT_BORDER_WIDTH));
  }

  private hideTip() {
    clearTimeout(this.hideTipTask)
    this.hideTipTask = setTimeout(() => {
      this.isTipShow = false
    }, 3000)
  }

  build() {
    Row() {
      Slider({
        direction: Axis.Vertical,
      })
        .height(this.slideHeight)
        .selectedColor(Color.Green)
        .trackColor('#5a5a5a')
        .trackThickness(10)
        .blockSize({ width: this.blockSize, height: this.blockSize })
        .selectedColor('#FF6103')
        .onChange((value: number, mode: SliderChangeMode) => {
          switch (mode) {
            case SliderChangeMode.Moving:
            case SliderChangeMode.Click:
              this.showTip(value);
              break;
            case SliderChangeMode.End:
              this.hideTip();
              break;
          }
        })
      if (this.isTipShow) {
        Text("i am tip!")
          .fontSize(12)
          .height(this.tipHeight)
          .offset({ y: this.tipsOffset })
          .fontColor(Color.White)
          .backgroundColor("#66000000")
          .padding(10)
          .borderRadius(5)
          .hitTestBehavior(HitTestMode.Transparent)
      }
    }
    .alignItems(VerticalAlign.Top)
    .padding(20)
    .height('100%')
    .width('100%')
  }
}